Example usage for android.widget LinearLayout addView

List of usage examples for android.widget LinearLayout addView

Introduction

In this page you can find the example usage for android.widget LinearLayout addView.

Prototype

public void addView(View child) 

Source Link

Document

Adds a child view.

Usage

From source file:com.sdspikes.fireworks.FireworksActivity.java

private void displayDiscardPiles() {
    LinearLayout currRow = ((LinearLayout) findViewById(R.id.discard_pile_row_1));
    LinearLayout row2 = ((LinearLayout) findViewById(R.id.discard_pile_row_2));
    currRow.removeAllViews();/*  w  ww  . jav a2 s  .  c  o m*/
    row2.removeAllViews();
    int maxInTopRow = mDiscardWidthR1 / MIN_CARD_WIDTH;

    int rowDivision = mTurnData.state.discarded.length;
    int totalDiscarded = 0;
    int topRow = 0;
    for (int i = 0; i < mTurnData.state.discarded.length; i++) {
        totalDiscarded += mTurnData.state.discarded[i].size();
        if (totalDiscarded <= maxInTopRow) {
            topRow = totalDiscarded;
        }
        if (totalDiscarded > maxInTopRow && rowDivision == mTurnData.state.discarded.length) {
            rowDivision = i;
        }
    }
    if (rowDivision == mTurnData.state.discarded.length) {
        row2.setVisibility(View.GONE);
    }
    if (totalDiscarded == 0) {
        return;
    }
    int width = mDiscardWidthR1 / topRow;
    for (int i = 0; i < mTurnData.state.discarded.length; i++) {
        for (int j = 0; j < mTurnData.state.discarded[i].size(); j++) {
            if (i == rowDivision) {
                currRow = row2;
                row2.setVisibility(View.VISIBLE);
                width = mDiscardWidthR2 / (totalDiscarded - topRow);
            }
            currRow.addView(makeNewCardTextView(width, mTurnData.state.discarded[i].get(j)));
        }
    }
}

From source file:com.ifoer.expeditionphone.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(Flags.FLAG8, Flags.FLAG8);
    contexts = this;
    this.loadSpecail = getIntent().getBooleanExtra("loadSpecail", false);
    FROMPATH = Constant.assestsPath;//from   w w  w  . j av a2 s .  co  m
    Locale locale = Locale.getDefault();
    country = MainMenuActivity.country;
    if (country == null) {
        country = locale.getCountry();
    }
    this.lanName = AndroidToLan.toLan(country);
    this.language = locale.getLanguage();
    Constant.language = locale.toString();
    if (this.loadSpecail) {
        setContentView(C0136R.layout.specia_function2);
        this.SpecialGridView = (GridView) findViewById(C0136R.id.main_WorkSpace);
        this.SpecialGridView.setHorizontalSpacing(15);
        this.SpecialGridView.setVerticalSpacing(15);
        this.SpecialGridView.setSelector(C0136R.color.transparent);
        this.SpecialGridView.setNumColumns(REQUEST_CIRCLE_ADD_IMAGE);
        this.mSpecilaBaseDiagAdapeter = createBaseDiagAdapter2(this.specialList);
        this.SpecialGridView.setAdapter(this.mSpecilaBaseDiagAdapeter);
        this.SpecialGridView.setOnItemClickListener(this);
    } else {
        setContentView(C0136R.layout.base_diagnose);
        LinearLayout lineLinear = (LinearLayout) findViewById(C0136R.id.diagnose_line2);
        this.mSlidePoinView = new SlidePointView(this);
        lineLinear.addView(this.mSlidePoinView);
        this.mSlidePoinView.postInvalidate();
        this.mChinaCarGridView = new GridView(this);
        this.mAsiaCarGridView = new GridView(this);
        this.mEuroCarGridView = new GridView(this);
        this.mAmericaCarGridView = new GridView(this);
        this.mAmericaCarGridView.setHorizontalSpacing(15);
        this.mAmericaCarGridView.setVerticalSpacing(15);
        this.mAsiaCarGridView.setHorizontalSpacing(15);
        this.mAsiaCarGridView.setVerticalSpacing(15);
        this.mEuroCarGridView.setHorizontalSpacing(15);
        this.mEuroCarGridView.setVerticalSpacing(15);
        this.mAmericaCarGridView.setVerticalScrollBarEnabled(false);
        this.mAsiaCarGridView.setVerticalScrollBarEnabled(false);
        this.mEuroCarGridView.setVerticalScrollBarEnabled(false);
        this.mAsiaCarGridView.setSelector(C0136R.color.transparent);
        this.mEuroCarGridView.setSelector(C0136R.color.transparent);
        this.mAmericaCarGridView.setSelector(C0136R.color.transparent);
        LayoutParams linearParams = new LayoutParams(-2, -2);
        linearParams.width = C0136R.dimen.itemSize;
        linearParams.height = C0136R.dimen.itemSize;
        this.mChinaCarGridView.setLayoutParams(linearParams);
        this.mAsiaCarGridView.setLayoutParams(linearParams);
        this.mEuroCarGridView.setLayoutParams(linearParams);
        this.mAmericaCarGridView.setLayoutParams(linearParams);
        this.mChinaCarGridView.setNumColumns(REQUEST_CIRCLE_ADD_IMAGE);
        this.mAsiaCarGridView.setNumColumns(REQUEST_CIRCLE_ADD_IMAGE);
        this.mEuroCarGridView.setNumColumns(REQUEST_CIRCLE_ADD_IMAGE);
        this.mAmericaCarGridView.setNumColumns(REQUEST_CIRCLE_ADD_IMAGE);
    }
    MyApplication.getInstance().addActivity(this);
    createMainActivity();
    MySharedPreferences.getSharedPref(this).edit().putString("CurrentPosition", Constant.language).commit();
    MySharedPreferences.setString(contexts, MySharedPreferences.generateOperatingRecord, Contact.RELATION_ASK);
    if (MainMenuActivity.database != null) {
        database = MainMenuActivity.database;
    } else {
        database = DBDao.getInstance(this).getConnection();
    }
    new Thread(new UpgradeRunnable(contexts)).start();
    registerBoradcastReceiver();
    try {
        dataDir = getPackageManager().getApplicationInfo(getPackageName(), 0).dataDir;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    try {
        serialPort = new SerialPortManager().getSerialPort();
    } catch (InvalidParameterException e2) {
        e2.printStackTrace();
    } catch (SecurityException e3) {
        e3.printStackTrace();
    } catch (Exception e4) {
        e4.printStackTrace();
    }
    if (MySharedPreferences.share == null) {
        MySharedPreferences.getSharedPref(this);
    }
}

From source file:com.fibrobook.viewpager.custom.CardFragment.java

public void symphtomsView(LinearLayout l) {

    LayoutParams params = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
            android.view.ViewGroup.LayoutParams.MATCH_PARENT, Gravity.TOP);

    ListView symphtomList = new ListView(getActivity());
    symphtomList.setLayoutParams(params);

    ArrayAdapter<Disease> adapter = new ArrayAdapter<Disease>(getActivity(),
            android.R.layout.simple_list_item_1, symphtoms);
    symphtomList.setAdapter(adapter);/* w  ww. j  ava 2s.  c  o  m*/
    symphtomList.setClickable(true);

    symphtomList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            ratingDialog = new Dialog(getActivity(), com.fibrobook.R.style.FullHeightDialog);
            ratingDialog.setContentView(com.fibrobook.R.layout.rating_dialog);
            ratingDialog.setCancelable(true);
            RatingBar ratingBar = (RatingBar) ratingDialog.findViewById(com.fibrobook.R.id.dialog_ratingbar);

            int i = 0;
            boolean exists = false;
            while (i < ds.size()) {
                if (symphtoms.get(position).getId() == ds.get(i).getDisease().getId()) {
                    ads = ds.get(i);
                    ratingBar.setRating(ads.getIntensity());
                    exists = true;
                    break;
                }
                i++;
            }
            if (!exists)
                ads = new SymphtomSummary(MainActivity.user, symphtoms.get(position), MainActivity.date);

            Button updateButton = (Button) ratingDialog.findViewById(com.fibrobook.R.id.rank_dialog_button);
            updateButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RatingBar ratingBar = (RatingBar) ratingDialog
                            .findViewById(com.fibrobook.R.id.dialog_ratingbar);
                    ads.setIntensity(ratingBar.getRating());
                    SymphtomSummaryDAO dao = new SymphtomSummaryDAO(getActivity());
                    dao.save(ads);
                    ds = dao.getSymphtomSummary(MainActivity.date);
                    dao.close();
                    ratingDialog.dismiss();
                }
            });
            ratingDialog.show();
        }

    });

    l.addView(symphtomList);
}

From source file:com.fibrobook.viewpager.custom.CardFragment.java

public void dayView(LinearLayout l) {

    LayoutParams params = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
            android.view.ViewGroup.LayoutParams.MATCH_PARENT, Gravity.TOP);

    ListView eventList = new ListView(getActivity());
    eventList.setLayoutParams(params);//ww  w .ja  v a 2 s  . co m

    ArrayAdapter<DailyEvent> adapter = new ArrayAdapter<DailyEvent>(getActivity(),
            android.R.layout.simple_list_item_1, dailyEvents);
    eventList.setAdapter(adapter);
    eventList.setClickable(true);

    eventList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            ratingDialog = new Dialog(getActivity(), com.fibrobook.R.style.FullHeightDialog);
            ratingDialog.setContentView(com.fibrobook.R.layout.rating_dialog);
            ratingDialog.setCancelable(true);
            RatingBar ratingBar = (RatingBar) ratingDialog.findViewById(com.fibrobook.R.id.dialog_ratingbar);

            int i = 0;
            boolean exists = false;
            while (i < des.size()) {
                if (dailyEvents.get(position).getId() == des.get(i).getDailyEvent().getId()) {
                    aes = des.get(i);
                    ratingBar.setRating(aes.getIntensity());
                    exists = true;
                    break;
                }
                i++;
            }
            if (!exists)
                aes = new DailyEventSummary(MainActivity.user, dailyEvents.get(position), MainActivity.date);

            Button updateButton = (Button) ratingDialog.findViewById(com.fibrobook.R.id.rank_dialog_button);
            updateButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RatingBar ratingBar = (RatingBar) ratingDialog
                            .findViewById(com.fibrobook.R.id.dialog_ratingbar);
                    aes.setIntensity(ratingBar.getRating());
                    DailyEventSummaryDAO dao = new DailyEventSummaryDAO(getActivity());
                    dao.save(aes);
                    des = dao.getDailySummary(MainActivity.date);
                    dao.close();
                    ratingDialog.dismiss();
                }
            });
            ratingDialog.show();
        }

    });

    l.addView(eventList);
}

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // it removes the title from the actionbar(more space for icons?)
    // this.getActionBar().setDisplayShowTitleEnabled(false);

    pixels5 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    LinearLayout parent = new LinearLayout(this);

    parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    parent.setOrientation(LinearLayout.VERTICAL);

    LinearLayout scrollViewParent = new LinearLayout(this);

    scrollViewParent.setLayoutParams(/*from w  ww  .j a  v a2 s  .c  o m*/
            new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    scrollViewParent.setOrientation(LinearLayout.HORIZONTAL);

    HorizontalScrollView predictionsHorizontalScrollView = new HorizontalScrollView(this);
    //predictionsHorizontalScrollView.setLayoutParams(new ViewGroup.LayoutParams());

    predictions = new LinearLayout(this);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
    params.gravity = Gravity.CENTER_VERTICAL;
    predictions.setLayoutParams(params);

    predictions.setOrientation(LinearLayout.HORIZONTAL);

    resetPredictionsView(predictions, true);
    predictionsHorizontalScrollView.addView(predictions);

    saveButton = new Button(this);
    saveButton.setText("Send Feedback");

    predictionsHorizontalScrollView.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 10.0f));

    saveButton.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f));

    saveButton.setVisibility(View.INVISIBLE);

    FrameLayout frameLayout = new FrameLayout(this);
    frameLayout
            .setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
    frameLayout.addView(saveButton);

    loader = new ProgressBar(this);
    loader.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    loader.setIndeterminate(true);
    loader.setVisibility(ProgressBar.INVISIBLE);

    frameLayout.addView(loader);

    scrollViewParent.addView(predictionsHorizontalScrollView);
    scrollViewParent.addView(frameLayout);

    contentView = new MyView(this);
    parent.addView(scrollViewParent);
    parent.addView(contentView);

    setContentView(parent);

    otherLabelOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.e("Clicked", "Other Label label '" + (String) view.getTag() + "'");
            sendScreenshot(false, feedbackType, (String) view.getTag());
        }
    };

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(DEFAULT_BRUSH_SIZE);

    // Where did these magic numbers come from? What do they mean? Can I change them? ~TheOpenSourceNinja
    // Absolutely random numbers in order to see the emboss. asd! ~Valerio
    mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);

    mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);

    if (isFirstTime()) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle(R.string.app_name);
        alert.setMessage(R.string.app_description);
        alert.setNegativeButton(R.string.continue_button, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Toast.makeText(getApplicationContext(), R.string.here_is_your_canvas, Toast.LENGTH_SHORT)
                        .show();
            }
        });

        alert.show();
    } else {
        Toast.makeText(getApplicationContext(), R.string.here_is_your_canvas, Toast.LENGTH_SHORT).show();
    }

    loadFromIntents();
}

From source file:com.facebook.android.friendsmash.ScoreboardFragment.java

private void populateScoreboard() {
    // Ensure all components are firstly removed from scoreboardContainer
    scoreboardContainer.removeAllViews();

    // Ensure the progress spinner is hidden
    progressContainer.setVisibility(View.INVISIBLE);

    // Ensure scoreboardEntriesList is not null and not empty first
    if (application.getScoreboardEntriesList() == null || application.getScoreboardEntriesList().size() <= 0) {
        closeAndShowError(getResources().getString(R.string.error_no_scores));
    } else {//from  ww  w .  j  a  v  a2  s.  c  o m
        // Iterate through scoreboardEntriesList, creating new UI elements for each entry
        int index = 0;
        Iterator<ScoreboardEntry> scoreboardEntriesIterator = application.getScoreboardEntriesList().iterator();
        while (scoreboardEntriesIterator.hasNext()) {
            // Get the current scoreboard entry
            final ScoreboardEntry currentScoreboardEntry = scoreboardEntriesIterator.next();

            // FrameLayout Container for the currentScoreboardEntry ...

            // Create and add a new FrameLayout to display the details of this entry
            FrameLayout frameLayout = new FrameLayout(getActivity());
            scoreboardContainer.addView(frameLayout);

            // Set the attributes for this frameLayout
            int topPadding = getResources().getDimensionPixelSize(R.dimen.scoreboard_entry_top_margin);
            frameLayout.setPadding(0, topPadding, 0, 0);

            // ImageView background image ...
            {
                // Create and add an ImageView for the background image to this entry
                ImageView backgroundImageView = new ImageView(getActivity());
                frameLayout.addView(backgroundImageView);

                // Set the image of the backgroundImageView
                String uri = "drawable/scores_stub_even";
                if (index % 2 != 0) {
                    // Odd entry
                    uri = "drawable/scores_stub_odd";
                }
                int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName());
                Drawable image = getResources().getDrawable(imageResource);
                backgroundImageView.setImageDrawable(image);

                // Other attributes of backgroundImageView to modify
                FrameLayout.LayoutParams backgroundImageViewLayoutParams = new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                int backgroundImageViewMarginTop = getResources()
                        .getDimensionPixelSize(R.dimen.scoreboard_background_imageview_margin_top);
                backgroundImageViewLayoutParams.setMargins(0, backgroundImageViewMarginTop, 0, 0);
                backgroundImageViewLayoutParams.gravity = Gravity.LEFT;
                if (index % 2 != 0) {
                    // Odd entry
                    backgroundImageViewLayoutParams.gravity = Gravity.RIGHT;
                }
                backgroundImageView.setLayoutParams(backgroundImageViewLayoutParams);
            }

            // ProfilePictureView of the current user ...
            {
                // Create and add a ProfilePictureView for the current user entry's profile picture
                ProfilePictureView profilePictureView = new ProfilePictureView(getActivity());
                frameLayout.addView(profilePictureView);

                // Set the attributes of the profilePictureView
                int profilePictureViewWidth = getResources()
                        .getDimensionPixelSize(R.dimen.scoreboard_profile_picture_view_width);
                FrameLayout.LayoutParams profilePictureViewLayoutParams = new FrameLayout.LayoutParams(
                        profilePictureViewWidth, profilePictureViewWidth);
                int profilePictureViewMarginLeft = 0;
                int profilePictureViewMarginTop = getResources()
                        .getDimensionPixelSize(R.dimen.scoreboard_profile_picture_view_margin_top);
                int profilePictureViewMarginRight = 0;
                int profilePictureViewMarginBottom = 0;
                if (index % 2 == 0) {
                    profilePictureViewMarginLeft = getResources()
                            .getDimensionPixelSize(R.dimen.scoreboard_profile_picture_view_margin_left);
                } else {
                    profilePictureViewMarginRight = getResources()
                            .getDimensionPixelSize(R.dimen.scoreboard_profile_picture_view_margin_right);
                }
                profilePictureViewLayoutParams.setMargins(profilePictureViewMarginLeft,
                        profilePictureViewMarginTop, profilePictureViewMarginRight,
                        profilePictureViewMarginBottom);
                profilePictureViewLayoutParams.gravity = Gravity.LEFT;
                if (index % 2 != 0) {
                    // Odd entry
                    profilePictureViewLayoutParams.gravity = Gravity.RIGHT;
                }
                profilePictureView.setLayoutParams(profilePictureViewLayoutParams);

                // Finally set the id of the user to show their profile pic
                profilePictureView.setProfileId(currentScoreboardEntry.getId());
            }

            // LinearLayout to hold the text in this entry

            // Create and add a LinearLayout to hold the TextViews
            LinearLayout textViewsLinearLayout = new LinearLayout(getActivity());
            frameLayout.addView(textViewsLinearLayout);

            // Set the attributes for this textViewsLinearLayout
            FrameLayout.LayoutParams textViewsLinearLayoutLayoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
            int textViewsLinearLayoutMarginLeft = 0;
            int textViewsLinearLayoutMarginTop = getResources()
                    .getDimensionPixelSize(R.dimen.scoreboard_textviews_linearlayout_margin_top);
            int textViewsLinearLayoutMarginRight = 0;
            int textViewsLinearLayoutMarginBottom = 0;
            if (index % 2 == 0) {
                textViewsLinearLayoutMarginLeft = getResources()
                        .getDimensionPixelSize(R.dimen.scoreboard_textviews_linearlayout_margin_left);
            } else {
                textViewsLinearLayoutMarginRight = getResources()
                        .getDimensionPixelSize(R.dimen.scoreboard_textviews_linearlayout_margin_right);
            }
            textViewsLinearLayoutLayoutParams.setMargins(textViewsLinearLayoutMarginLeft,
                    textViewsLinearLayoutMarginTop, textViewsLinearLayoutMarginRight,
                    textViewsLinearLayoutMarginBottom);
            textViewsLinearLayoutLayoutParams.gravity = Gravity.LEFT;
            if (index % 2 != 0) {
                // Odd entry
                textViewsLinearLayoutLayoutParams.gravity = Gravity.RIGHT;
            }
            textViewsLinearLayout.setLayoutParams(textViewsLinearLayoutLayoutParams);
            textViewsLinearLayout.setOrientation(LinearLayout.VERTICAL);

            // TextView with the position and name of the current user
            {
                // Set the text that should go in this TextView first
                int position = index + 1;
                String currentScoreboardEntryTitle = position + ". " + currentScoreboardEntry.getName();

                // Create and add a TextView for the current user position and first name
                TextView titleTextView = new TextView(getActivity());
                textViewsLinearLayout.addView(titleTextView);

                // Set the text and other attributes for this TextView
                titleTextView.setText(currentScoreboardEntryTitle);
                titleTextView.setTextAppearance(getActivity(), R.style.ScoreboardPlayerNameFont);
            }

            // TextView with the score of the current user
            {
                // Create and add a TextView for the current user score
                TextView scoreTextView = new TextView(getActivity());
                textViewsLinearLayout.addView(scoreTextView);

                // Set the text and other attributes for this TextView
                scoreTextView.setText("Score: " + currentScoreboardEntry.getScore());
                scoreTextView.setTextAppearance(getActivity(), R.style.ScoreboardPlayerScoreFont);
            }

            // Finally make this frameLayout clickable so that a game starts with the user smashing
            // the user represented by this frameLayout in the scoreContainer
            frameLayout.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        Bundle bundle = new Bundle();
                        bundle.putString("user_id", currentScoreboardEntry.getId());

                        Intent i = new Intent();
                        i.putExtras(bundle);

                        getActivity().setResult(Activity.RESULT_FIRST_USER, i);
                        getActivity().finish();
                        return false;
                    } else {
                        return true;
                    }
                }

            });

            // Increment the index before looping back
            index++;
        }
    }
}

From source file:com.httrack.android.HTTrackActivity.java

private TextView addEmptyLineToLayout(final LinearLayout layout) {
    final TextView text = new TextView(this);

    // Span to the width
    text.setWidth(LayoutParams.FILL_PARENT);
    text.setHeight(LayoutParams.WRAP_CONTENT);

    // Single line, with optional ellipsis (...) on the middle
    text.setSingleLine();//from w  w w  .  j a v  a  2 s .co m
    text.setEllipsize(TextUtils.TruncateAt.MIDDLE);
    layout.addView(text);

    // Return new widget
    return text;
}

From source file:com.aware.Aware.java

/**
 * Given a plugin's package name, fetch the context card for reuse.
 * @param context: application context/*from  w w  w .  ja v a 2 s  .c om*/
 * @param package_name: plugin's package name
 * @return View for reuse (instance of LinearLayout)
 */
public static View getContextCard(final Context context, final String package_name) {

    if (!isClassAvailable(context, package_name, "ContextCard")) {
        return null;
    }

    String ui_class = package_name + ".ContextCard";
    LinearLayout card = new LinearLayout(context);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    card.setLayoutParams(params);
    card.setOrientation(LinearLayout.VERTICAL);

    try {
        Context packageContext = context.createPackageContext(package_name,
                Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);

        Class<?> fragment_loader = packageContext.getClassLoader().loadClass(ui_class);
        Object fragment = fragment_loader.newInstance();
        Method[] allMethods = fragment_loader.getDeclaredMethods();
        Method m = null;
        for (Method mItem : allMethods) {
            String mName = mItem.getName();
            if (mName.contains("getContextCard")) {
                mItem.setAccessible(true);
                m = mItem;
                break;
            }
        }

        View ui = (View) m.invoke(fragment, packageContext);
        if (ui != null) {
            //Check if plugin has settings. If it does, tapping the card shows the settings
            if (isClassAvailable(context, package_name, "Settings")) {
                ui.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent open_settings = new Intent();
                        open_settings.setClassName(package_name, package_name + ".Settings");
                        open_settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(open_settings);
                    }
                });
            }

            //Set card look-n-feel
            ui.setBackgroundColor(Color.WHITE);
            ui.setPadding(20, 20, 20, 20);
            card.addView(ui);

            LinearLayout shadow = new LinearLayout(context);
            LayoutParams params_shadow = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            params_shadow.setMargins(0, 0, 0, 10);
            shadow.setBackgroundColor(context.getResources().getColor(R.color.card_shadow));
            shadow.setMinimumHeight(5);
            shadow.setLayoutParams(params_shadow);
            card.addView(shadow);

            return card;
        } else {
            return null;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.hughes.android.dictionary.DictionaryActivity.java

void onLanguageButtonLongClick(final Context context) {
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.select_dictionary_dialog);
    dialog.setTitle(R.string.selectDictionary);

    final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);

    ListView listView = (ListView) dialog.findViewById(android.R.id.list);
    final Button button = new Button(listView.getContext());
    final String name = getString(R.string.dictionaryManager);
    button.setText(name);//from  w ww.j  a va2  s . c o m
    final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
            DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
        @Override
        protected void onGo() {
            dialog.dismiss();
            DictionaryActivity.this.finish();
        }
    };
    button.setOnClickListener(intentLauncher);
    listView.addHeaderView(button);

    listView.setAdapter(new BaseAdapter() {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final DictionaryInfo dictionaryInfo = getItem(position);

            final LinearLayout result = new LinearLayout(parent.getContext());

            for (int i = 0; i < dictionaryInfo.indexInfos.size(); ++i) {
                final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
                final View button = application.createButton(parent.getContext(), dictionaryInfo, indexInfo);
                final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
                        getLaunchIntent(getApplicationContext(),
                                application.getPath(dictionaryInfo.uncompressedFilename), indexInfo.shortName,
                                searchView.getQuery().toString())) {
                    @Override
                    protected void onGo() {
                        dialog.dismiss();
                        DictionaryActivity.this.finish();
                    }
                };
                button.setOnClickListener(intentLauncher);
                if (i == indexIndex && dictFile != null
                        && dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
                    button.setPressed(true);
                }
                result.addView(button);
            }

            final TextView nameView = new TextView(parent.getContext());
            final String name = application.getDictionaryName(dictionaryInfo.uncompressedFilename);
            nameView.setText(name);
            final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.width = 0;
            layoutParams.weight = 1.0f;
            nameView.setLayoutParams(layoutParams);
            nameView.setGravity(Gravity.CENTER_VERTICAL);
            result.addView(nameView);
            return result;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public DictionaryInfo getItem(int position) {
            return installedDicts.get(position);
        }

        @Override
        public int getCount() {
            return installedDicts.size();
        }
    });
    dialog.show();
}

From source file:foam.jellyfish.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {//  w  w  w . ja  v  a 2  s.  c  o  m

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        Log.i("starwisp", "Update: " + type + " " + id + " " + token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            if (m_NetworkManager.state == NetworkManager.State.IDLE) {
                final String name = arr.getString(3);
                final String ssid = arr.getString(5);
                m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            }
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            Log.i("starwisp", "button-grid update");
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                Log.i("starwisp", "button-grid contents");
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            Log.i("starwisp", "text-view...");
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        /*
                    if (type.equals("canvas")) {
        StarwispCanvas v = (StarwispCanvas)vv;
        if (token.equals("drawlist")) {
            v.SetDrawList(arr.getJSONArray(3));
        }
        return;
                    }
                
                    if (type.equals("camera-preview")) {
        final CameraPreview v = (CameraPreview)vv;
                
        if (token.equals("take-picture")) {
            final String path = ((StarwispActivity)ctx).m_AppDir+arr.getString(3);
                
            v.TakePicture(
                new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path+datetime + ".jpg";
                        SaveData(filename,data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
        }
                
        if (token.equals("shutdown")) {
            v.Shutdown();
        }
                
        return;
                    }
        */
        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx,
                        android.R.layout.simple_spinner_item, spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        try {
                            CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing data " + e.toString());
    }
}