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, int index) 

Source Link

Document

Adds a child view.

Usage

From source file:com.joravasal.comicagg.ComicDetailFragment.java

@SuppressLint({ "NewApi" })
@Override/*from  w  w  w .j  a va 2 s .c o  m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_comic_detail, container, false);
    if (comicItem == null && savedInstanceState.containsKey(ARG_ITEM_ID)) {
        comicItem = new ComicItem(savedInstanceState.getString(ARG_ITEM_ID),
                savedInstanceState.getString("comicname"), savedInstanceState.getString("comicurl"),
                savedInstanceState.getString("unreadcount"));
    }
    int unread = Integer.parseInt(comicItem.unreadCount);
    if (unread == 0) {
        rootView.findViewById(R.id.vote_bar).setVisibility(View.GONE);
    }
    LinearLayout stripList = (LinearLayout) rootView.findViewById(R.id.strips_list);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

    if (comicItem.id.equals(ComicStripsContent.id) && ComicStripsContent.ITEMS.size() > unread) {
        unread = ComicStripsContent.ITEMS.size();
    }
    for (int i = 1; i < unread; i++) {
        ImageView iv = new ImageView(getActivity());
        iv.setId(Integer.MAX_VALUE - i);
        iv.setPadding(16, 16, 16, 0);
        iv.setContentDescription(getString(R.string.strip_description));
        iv.setAdjustViewBounds(true);

        iv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO check if there is need of opening? or always open?
                openFullscreenStrip(v);
            }
        });

        TextView tv = new TextView(getActivity());
        tv.setId(i);
        tv.setPadding(16, 4, 16, 4);
        tv.setGravity(Gravity.CENTER);

        stripList.addView(iv, layoutParams);
        stripList.addView(tv, layoutParams);
    }

    if (!comicItem.id.equals(ComicStripsContent.id)) {
        new GetComicsStrips(comicItem.id, unread, rootView).execute();
    } else {
        new GetComicsStrips(comicItem.id, unread, rootView).onPostExecute(null);
    }
    if (savedInstanceState != null && savedInstanceState.containsKey(VERTICAL_SCROLLING_POSITION)
            && VERSION.SDK_INT >= 14) {
        rootView.findViewById(R.id.comic_scrollView).scrollTo(0,
                savedInstanceState.getInt(VERTICAL_SCROLLING_POSITION));
    }
    return rootView;
}

From source file:com.githang.androidkit.app.IntroActivity.java

/**
 * //w  w  w  .  ja va  2 s. c  om
 */
private void createContentView() {
    // ?
    mIntroResource = new IntroResource();
    setIntroViews(mIntroResource);

    // 
    RelativeLayout rootView = new RelativeLayout(this);
    rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    // 
    mViewPager = new ViewPager(this);
    RelativeLayout.LayoutParams pagerParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    rootView.addView(mViewPager, pagerParams);

    // 
    LinearLayout indicatorLayout = new LinearLayout(this);
    RelativeLayout.LayoutParams indicatorParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    indicatorParams.bottomMargin = mIntroResource.indicatorMarginBottom;
    indicatorParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    indicatorParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
    indicatorLayout.setLayoutParams(indicatorParams);
    indicatorLayout.setOrientation(LinearLayout.HORIZONTAL);

    // 
    int indicatorCount = mIntroResource.views.size();
    int padding = mIntroResource.indicatorImagePadding;
    mIndicator = new ArrayList<ImageView>();
    for (int i = 0; i < indicatorCount; i++) {
        ImageView imageView = new ImageView(this);
        LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        imageView.setPadding(padding, padding, padding, padding);
        imageView.setClickable(true);
        imageView.setOnClickListener(this);
        imageView.setImageResource(mIntroResource.indicatorNoSelectedId);
        imageView.setTag(i);
        mIndicator.add(imageView);
        indicatorLayout.addView(imageView, imageParams);
    }

    rootView.addView(indicatorLayout);

    setContentView(rootView);
}

From source file:com.devwang.logcabin.LogCabinMainActivity.java

private void toastDisplay(Context context, CharSequence text, int gravity, int ResImgId, int duration) {
    Toast toast = Toast.makeText(context, text, duration);
    if (gravity != 0) {
        switch (gravity) {
        case Gravity.CENTER:
            toast.setGravity(Gravity.CENTER, 0, 0);//  x,y0
            break;
        case Gravity.FILL:
            toast.setGravity(Gravity.FILL, 0, 0);//  x,y0
            break;
        case Gravity.BOTTOM:
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            break;
        default:// w w  w .ja  v a  2  s. c  om
            break;
        }
    }
    if (ResImgId != 0) {
        LinearLayout toastView = (LinearLayout) toast.getView();
        ImageView imageCodeProject = new ImageView(getApplicationContext());
        imageCodeProject.setImageResource(ResImgId);
        toastView.addView(imageCodeProject, 0);
    }

    toast.show();
}

From source file:com.handlerexploit.news.fragments.WeatherFragment.java

private void render(WeatherInfo weatherInfo) {
    Activity activity = getActivity();/*from  w ww  . ja  v  a 2 s  .c o m*/
    if (activity != null && weatherInfo != null) {
        View root = getView();

        TextView city = (TextView) root.findViewById(R.id.city);
        city.setText(weatherInfo.getCity());

        CurrentWeather currentWeather = weatherInfo.getCurrentWeather();

        RemoteImageView icon = (RemoteImageView) root.findViewById(R.id.icon);
        int resId = activity.getResources().getIdentifier(currentWeather.getIcon(), "drawable",
                activity.getPackageName());
        if (resId != 0) {
            ((ImageView) activity.findViewById(R.id.weather_small_logo)).setImageResource(resId);
            icon.setImageResource(resId);
        } else {
            ((ImageView) activity.findViewById(R.id.weather_small_logo)).setImageResource(R.drawable.unknown);
            icon.setImageResource(R.drawable.unknown);
        }

        TextView temp = (TextView) root.findViewById(R.id.temp);
        temp.setText(currentWeather.getTempF() + " \u00B0F | " + currentWeather.getTempC() + " \u00B0C");
        ((TextView) activity.findViewById(R.id.weather_small_text))
                .setText(currentWeather.getTempF() + "\u00B0");

        TextView condition = (TextView) root.findViewById(R.id.condition);
        String conditionText = currentWeather.getCondition();
        if (conditionText != null && !conditionText.equals("")) {
            condition.setText(conditionText);
        } else {
            condition.setText("N/A");
        }

        TextView windCondition = (TextView) root.findViewById(R.id.windCondition);
        windCondition.setText(currentWeather.getWindCondition());

        TextView humidity = (TextView) root.findViewById(R.id.humidity);
        humidity.setText(currentWeather.getHumidity());

        LinearLayout forcastConditions = (LinearLayout) root.findViewById(R.id.forcastConditions);
        forcastConditions.removeAllViews();

        LayoutInflater inflater = LayoutInflater.from(activity);
        LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        params.weight = 1f;

        ArrayList<Condition> forcastArray = weatherInfo.getForcastConditions();
        for (int i = 0; i < forcastArray.size(); i++) {
            Condition forcastCondition = forcastArray.get(i);
            View forcastRoot = inflater.inflate(R.layout.fragment_weather_condition_item, null);

            TextView forcastDay = (TextView) forcastRoot.findViewById(R.id.day);
            forcastDay.setText(forcastCondition.getDay());

            RemoteImageView forcastIcon = (RemoteImageView) forcastRoot.findViewById(R.id.icon);
            int forcastResId = activity.getResources().getIdentifier(forcastCondition.getIcon(), "drawable",
                    activity.getPackageName());
            if (forcastResId != 0) {
                forcastIcon.setImageResource(forcastResId);
            } else {
                forcastIcon.setImageResource(R.drawable.unknown);
            }

            TextView forcastHigh = (TextView) forcastRoot.findViewById(R.id.high);
            forcastHigh.setText(forcastCondition.getHigh() + "\u00B0");

            TextView forcastLow = (TextView) forcastRoot.findViewById(R.id.low);
            forcastLow.setText(forcastCondition.getLow() + "\u00B0");

            forcastConditions.addView(forcastRoot, params);
        }
    }
}

From source file:com.sft.blackcatapp.SearchCoachActivity.java

private void showOpenCityPopupWindow(View parent) {
    if (openCityPopupWindow == null) {
        LinearLayout popWindowLayout = (LinearLayout) View.inflate(mContext, R.layout.pop_window, null);
        popWindowLayout.removeAllViews();
        // LinearLayout popWindowLayout = new LinearLayout(mContext);
        popWindowLayout.setOrientation(LinearLayout.VERTICAL);
        ListView OpenCityListView = new ListView(mContext);
        OpenCityListView.setDividerHeight(0);
        OpenCityListView.setCacheColorHint(android.R.color.transparent);
        OpenCityListView.setOnItemClickListener(new OnItemClickListener() {

            @Override//from   w ww  . ja  v  a2  s  .c  o  m
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OpenCityVO selectCity = openCityList.get(position);
                System.out.println(selectCity.getName());
                cityname = selectCity.getName().replace("", "");
                licensetype = "";
                coachname = "";
                ordertype = "0";
                index = 1;
                obtainCaoch();
                openCityPopupWindow.dismiss();
                openCityPopupWindow = null;
            }
        });
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindowLayout.addView(OpenCityListView, param);
        OpenCityAdapter openCityAdapter = new OpenCityAdapter(mContext, openCityList);
        OpenCityListView.setAdapter(openCityAdapter);

        openCityPopupWindow = new PopupWindow(popWindowLayout, 130, LayoutParams.WRAP_CONTENT);
    }
    openCityPopupWindow.setFocusable(true);
    openCityPopupWindow.setOutsideTouchable(true);
    // Back???
    openCityPopupWindow.setBackgroundDrawable(new BitmapDrawable());

    openCityPopupWindow.showAsDropDown(parent);
}

From source file:com.common.widget.pageindicator.C_TabPageIndicator.java

@SuppressLint("NewApi")
// private void addTab(int index, CharSequence text, int iconResId) {
// final TabView tabView = new TabView(getContext());
// tabView.mIndex = index;
// tabView.setFocusable(true);
// tabView.setOnClickListener(mTabClickListener);
// tabView.setText(text);
// if (iconResId != 0) {
// // tabView.setCompoundDrawablePadding(
// // (int) getResources().getDimension(R.dimen.margin1));
// tabView.setCompoundDrawablesWithIntrinsicBounds(0, iconResId, 0, 0);
// // setTabIcon(tabView, iconResId);
// }//from   ww w  .j a  va2 s.  c o  m
// if (deviceWeight) {
// mTabLayout.addView(tabView, new LinearLayout.LayoutParams(0,
// MATCH_PARENT, 1));
// } else {
// LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
// WRAP_CONTENT, MATCH_PARENT);
// lp.leftMargin = 10;
// lp.rightMargin = 10;
// mTabLayout.addView(tabView, lp);
// }
// }
private void addTab(int index, CharSequence text, int iconResId) {
    if (deviceWeight) { // tab  ? Layout
        LinearLayout layout = new LinearLayout(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(WRAP_CONTENT, MATCH_PARENT, 1);
        //???GG
        layout.setBackgroundColor(C_ResUtil.getSrcColor(R.color.full_transparent));
        layout.setGravity(Gravity.CENTER);
        // TextView
        final TabView tabView = new TabView(getContext());
        tabView.mIndex = index;
        // ?layoutLayout???
        tabView.setFocusable(false);
        tabView.setClickable(false);
        tabView.setOnClickListener(mTabClickListener);
        tabView.setText(text);
        if (iconResId != 0) {
            //             tabView.setCompoundDrawablesWithIntrinsicBounds(0, iconResId,
            //             0, 0);
            //                tabView.setPaddingRelative(10, 10, 10, 10);
            //                tabView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
            //                        iconResId, 0);
            tabView.setBackgroundResource(iconResId);
        }
        tabView.setPadding(C_ResUtil.getDimens(R.dimen._10dp), 0, C_ResUtil.getDimens(R.dimen._10dp), 0);
        LinearLayout.LayoutParams tvlp = new LinearLayout.LayoutParams(WRAP_CONTENT,
                C_ResUtil.getDimens(R.dimen._22dp));
        tvlp.rightMargin = C_ResUtil.getDimens(R.dimen._2dp);
        tvlp.leftMargin = C_ResUtil.getDimens(R.dimen._2dp);
        layout.addView(tabView, tvlp);
        layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                tabView.performClick();
            }
        });
        // TextView
        mTabLayout.addView(layout, lp);
    } else {
        final TabView tabView = new TabView(getContext());
        tabView.mIndex = index;
        tabView.setFocusable(true);
        tabView.setOnClickListener(mTabClickListener);
        tabView.setText(text);
        if (iconResId != 0) {
            // tabView.setCompoundDrawablePadding(
            // (int) getResources().getDimension(R.dimen.margin1));
            // tabView.setCompoundDrawablesWithIntrinsicBounds(0, iconResId,
            // 0, 0);
            tabView.setPaddingRelative(10, 10, 10, 10);
            tabView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, iconResId, 0);
            // setTabIcon(tabView, iconResId);
        }
        tabView.setPadding(C_ResUtil.getDimens(R.dimen._10dp), 0, C_ResUtil.getDimens(R.dimen._10dp), 0);
        // if (deviceWeight) {
        // mTabLayout.addView(tabView, new LinearLayout.LayoutParams(0,
        // MATCH_PARENT, 1));
        // } else {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(WRAP_CONTENT,
                C_ResUtil.getDimens(R.dimen._22dp));
        lp.leftMargin = C_ResUtil.getDimens(R.dimen._2dp);
        lp.rightMargin = C_ResUtil.getDimens(R.dimen._2dp);
        //         mTabLayout.addView(tabView, lp);
        // }
    }
}

From source file:com.t2.compassionMeditation.Graphs1Activity.java

/**
 * Sets up all parameters for display of both the chart on the screen 
 * AND a color coded display of the parameters and their values 
 *//*  ww w  . j  a v  a 2s.  co m*/
private void generateChart() {
    // Set up chart
    XYMultipleSeriesDataset deviceDataset = new XYMultipleSeriesDataset();
    XYMultipleSeriesRenderer deviceRenderer = new XYMultipleSeriesRenderer();

    LinearLayout layout = (LinearLayout) findViewById(R.id.deviceChart);
    if (mDeviceChartView != null) {
        layout.removeView(mDeviceChartView);
    }
    if (true) {
        mDeviceChartView = ChartFactory.getLineChartView(this, deviceDataset, deviceRenderer);
        mDeviceChartView.setBackgroundColor(Color.BLACK);
        layout.addView(mDeviceChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    }

    deviceRenderer.setShowLabels(false);
    deviceRenderer.setMargins(new int[] { 0, 5, 5, 0 });
    deviceRenderer.setShowAxes(true);
    deviceRenderer.setShowLegend(false);

    deviceRenderer.setZoomEnabled(false, false);
    deviceRenderer.setPanEnabled(false, false);
    deviceRenderer.setYAxisMin(0);
    deviceRenderer.setYAxisMax(100);

    SpannableStringBuilder sMeasuresText = new SpannableStringBuilder("Displaying: ");

    ArrayList<Long> visibleIds = getVisibleIds(KEY_NAME);

    int keyCount = mBioParameters.size();
    keyCount = mBioParameters.size();

    int lineNum = 0;
    for (int i = 0; i < mBioParameters.size(); ++i) {
        GraphBioParameter item = mBioParameters.get(i);

        item.visible = visibleIds.contains(item.id);
        if (!item.visible) {
            continue;
        }

        deviceDataset.addSeries(item.series);
        item.color = getKeyColor(i, keyCount);

        // Add name of the measure to the displayed text field
        ForegroundColorSpan fcs = new ForegroundColorSpan(item.color);
        int start = sMeasuresText.length();
        sMeasuresText.append(mBioParameters.get(i).title1 + ", ");
        int end = sMeasuresText.length();
        sMeasuresText.setSpan(fcs, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        if (sMeasuresText.length() > 40 && lineNum == 0) {
            lineNum++;
        }

        XYSeriesRenderer seriesRenderer = new XYSeriesRenderer();
        seriesRenderer.setColor(item.color);
        seriesRenderer.setPointStyle(PointStyle.CIRCLE);

        deviceRenderer.addSeriesRenderer(seriesRenderer);
    }

    mMeasuresDisplayText.setText(sMeasuresText);
}

From source file:com.asksven.betterbatterystats.StatsActivity.java

public Dialog getShareDialog() {

    final ArrayList<Integer> selectedSaveActions = new ArrayList<Integer>();

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean saveDumpfile = sharedPrefs.getBoolean("save_dumpfile", true);
    boolean saveLogcat = sharedPrefs.getBoolean("save_logcat", false);
    boolean saveDmesg = sharedPrefs.getBoolean("save_dmesg", false);

    if (saveDumpfile) {
        selectedSaveActions.add(0);/*  www  .ja v a 2  s. c o m*/
    }
    if (saveLogcat) {
        selectedSaveActions.add(1);
    }
    if (saveDmesg) {
        selectedSaveActions.add(2);
    }

    //----
    LinearLayout layout = new LinearLayout(this);
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(parms);

    layout.setGravity(Gravity.CLIP_VERTICAL);
    layout.setPadding(2, 2, 2, 2);

    final TextView editTitle = new TextView(StatsActivity.this);
    editTitle.setText(R.string.share_dialog_edit_title);
    editTitle.setPadding(40, 40, 40, 40);
    editTitle.setGravity(Gravity.LEFT);
    editTitle.setTextSize(20);

    final EditText editDescription = new EditText(StatsActivity.this);

    LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    tv1Params.bottomMargin = 5;
    layout.addView(editTitle, tv1Params);
    layout.addView(editDescription, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));

    //----

    // Set the dialog title
    builder.setTitle(R.string.title_share_dialog)
            .setMultiChoiceItems(R.array.saveAsLabels, new boolean[] { saveDumpfile, saveLogcat, saveDmesg },
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            if (isChecked) {
                                // If the user checked the item, add it to the
                                // selected items
                                selectedSaveActions.add(which);
                            } else if (selectedSaveActions.contains(which)) {
                                // Else, if the item is already in the array,
                                // remove it
                                selectedSaveActions.remove(Integer.valueOf(which));
                            }
                        }
                    })
            .setView(layout)
            // Set the action buttons
            .setPositiveButton(R.string.label_button_share, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    ArrayList<Uri> attachements = new ArrayList<Uri>();

                    Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName,
                            StatsActivity.this);
                    Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName,
                            StatsActivity.this);

                    Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);

                    // save as text is selected
                    if (selectedSaveActions.contains(0)) {
                        attachements.add(reading.writeDumpfile(StatsActivity.this,
                                editDescription.getText().toString()));
                    }
                    // save logcat if selected
                    if (selectedSaveActions.contains(1)) {
                        attachements.add(StatsProvider.getInstance().writeLogcatToFile());
                    }
                    // save dmesg if selected
                    if (selectedSaveActions.contains(2)) {
                        attachements.add(StatsProvider.getInstance().writeDmesgToFile());
                    }

                    if (!attachements.isEmpty()) {
                        Intent shareIntent = new Intent();
                        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachements);
                        shareIntent.setType("text/*");
                        startActivity(Intent.createChooser(shareIntent, "Share info to.."));
                    }
                }
            }).setNeutralButton(R.string.label_button_save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    try {
                        Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName,
                                StatsActivity.this);
                        Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName,
                                StatsActivity.this);

                        Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);

                        // save as text is selected
                        if (selectedSaveActions.contains(0)) {
                            reading.writeDumpfile(StatsActivity.this, editDescription.getText().toString());
                        }
                        // save logcat if selected
                        if (selectedSaveActions.contains(1)) {
                            StatsProvider.getInstance().writeLogcatToFile();
                        }
                        // save dmesg if selected
                        if (selectedSaveActions.contains(2)) {
                            StatsProvider.getInstance().writeDmesgToFile();
                        }

                        Snackbar.make(findViewById(android.R.id.content), getString(R.string.info_files_written)
                                + ": " + StatsProvider.getWritableFilePath(), Snackbar.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Log.e(TAG, "an error occured writing files: " + e.getMessage());
                        Snackbar.make(findViewById(android.R.id.content), R.string.info_files_write_error,
                                Snackbar.LENGTH_LONG).show();
                    }

                }
            }).setNegativeButton(R.string.label_button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });

    return builder.create();
}

From source file:android.support.v7.widget.ListPopupWindow.java

/**
 * <p>Builds the popup window's content and returns the height the popup
 * should have. Returns -1 when the content already exists.</p>
 *
 * @return the content's height or -1 if content already exists
 *///from  w  w  w .  jav a2s  .  co  m
private int buildDropDown() {
    ViewGroup dropDownView;
    int otherHeights = 0;

    if (mDropDownList == null) {
        Context context = mContext;

        /**
         * This Runnable exists for the sole purpose of checking if the view layout has got
         * completed and if so call showDropDown to display the drop down. This is used to show
         * the drop down as soon as possible after user opens up the search dialog, without
         * waiting for the normal UI pipeline to do it's job which is slower than this method.
         */
        mShowDropDownRunnable = new Runnable() {
            public void run() {
                // View layout should be all done before displaying the drop down.
                View view = getAnchorView();
                if (view != null && view.getWindowToken() != null) {
                    show();
                }
            }
        };

        mDropDownList = new DropDownListView(context, !mModal);
        if (mDropDownListHighlight != null) {
            mDropDownList.setSelector(mDropDownListHighlight);
        }
        mDropDownList.setAdapter(mAdapter);
        mDropDownList.setOnItemClickListener(mItemClickListener);
        mDropDownList.setFocusable(true);
        mDropDownList.setFocusableInTouchMode(true);
        mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (position != -1) {
                    DropDownListView dropDownList = mDropDownList;

                    if (dropDownList != null) {
                        dropDownList.mListSelectionHidden = false;
                    }
                }
            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        mDropDownList.setOnScrollListener(mScrollListener);

        if (mItemSelectedListener != null) {
            mDropDownList.setOnItemSelectedListener(mItemSelectedListener);
        }

        dropDownView = mDropDownList;

        View hintView = mPromptView;
        if (hintView != null) {
            // if a hint has been specified, we accomodate more space for it and
            // add a text view in the drop down menu, at the bottom of the list
            LinearLayout hintContainer = new LinearLayout(context);
            hintContainer.setOrientation(LinearLayout.VERTICAL);

            LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f);

            switch (mPromptPosition) {
            case POSITION_PROMPT_BELOW:
                hintContainer.addView(dropDownView, hintParams);
                hintContainer.addView(hintView);
                break;

            case POSITION_PROMPT_ABOVE:
                hintContainer.addView(hintView);
                hintContainer.addView(dropDownView, hintParams);
                break;

            default:
                Log.e(TAG, "Invalid hint position " + mPromptPosition);
                break;
            }

            // measure the hint's height to find how much more vertical space
            // we need to add to the drop down's height
            int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST);
            int heightSpec = MeasureSpec.UNSPECIFIED;
            hintView.measure(widthSpec, heightSpec);

            hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams();
            otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin;

            dropDownView = hintContainer;
        }

        mPopup.setContentView(dropDownView);
    } else {
        dropDownView = (ViewGroup) mPopup.getContentView();
        final View view = mPromptView;
        if (view != null) {
            LinearLayout.LayoutParams hintParams = (LinearLayout.LayoutParams) view.getLayoutParams();
            otherHeights = view.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin;
        }
    }

    // getMaxAvailableHeight() subtracts the padding, so we put it back
    // to get the available height for the whole window
    int padding = 0;
    Drawable background = mPopup.getBackground();
    if (background != null) {
        background.getPadding(mTempRect);
        padding = mTempRect.top + mTempRect.bottom;

        // If we don't have an explicit vertical offset, determine one from the window
        // background so that content will line up.
        if (!mDropDownVerticalOffsetSet) {
            mDropDownVerticalOffset = -mTempRect.top;
        }
    } else {
        mTempRect.setEmpty();
    }

    // Max height available on the screen for a popup.
    boolean ignoreBottomDecorations = mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED;
    final int maxHeight = mPopup.getMaxAvailableHeight(getAnchorView(),
            mDropDownVerticalOffset /*, ignoreBottomDecorations*/);

    if (mDropDownAlwaysVisible || mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) {
        return maxHeight + padding;
    }

    final int childWidthSpec;
    switch (mDropDownWidth) {
    case ViewGroup.LayoutParams.WRAP_CONTENT:
        childWidthSpec = MeasureSpec.makeMeasureSpec(
                mContext.getResources().getDisplayMetrics().widthPixels - (mTempRect.left + mTempRect.right),
                MeasureSpec.AT_MOST);
        break;
    case ViewGroup.LayoutParams.MATCH_PARENT:
        childWidthSpec = MeasureSpec.makeMeasureSpec(
                mContext.getResources().getDisplayMetrics().widthPixels - (mTempRect.left + mTempRect.right),
                MeasureSpec.EXACTLY);
        break;
    default:
        childWidthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.EXACTLY);
        break;
    }

    final int listContent = mDropDownList.measureHeightOfChildrenCompat(childWidthSpec, 0,
            DropDownListView.NO_POSITION, maxHeight - otherHeights, -1);
    // add padding only if the list has items in it, that way we don't show
    // the popup if it is not needed
    if (listContent > 0)
        otherHeights += padding;

    return listContent + otherHeights;
}

From source file:com.cliff.material.widget.ListPopupWindow.java

/**
 * <p>Builds the popup window's content and returns the height the popup
 * should have. Returns -1 when the content already exists.</p>
 *
 * @return the content's height or -1 if content already exists
 *///www . j a v a2 s.  co m
private int buildDropDown() {
    int otherHeights = 0;

    if (mDropDownList == null) {
        ViewGroup dropDownView;
        Context context = mContext;

        /**
         * This Runnable exists for the sole purpose of checking if the view layout has got
         * completed and if so call showDropDown to display the drop down. This is used to show
         * the drop down as soon as possible after user opens up the search dialog, without
         * waiting for the normal UI pipeline to do it's job which is slower than this method.
         */
        mShowDropDownRunnable = new Runnable() {
            public void run() {
                // View layout should be all done before displaying the drop down.
                View view = getAnchorView();
                if (view != null && view.getWindowToken() != null) {
                    show();
                }
            }
        };

        mDropDownList = new DropDownListView(context, !mModal);
        if (mDropDownListHighlight != null) {
            mDropDownList.setSelector(mDropDownListHighlight);
        }
        mDropDownList.setAdapter(mAdapter);
        mDropDownList.setOnItemClickListener(mItemClickListener);
        mDropDownList.setFocusable(true);
        mDropDownList.setFocusableInTouchMode(true);
        mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (position != -1) {
                    DropDownListView dropDownList = mDropDownList;

                    if (dropDownList != null) {
                        dropDownList.mListSelectionHidden = false;
                    }
                }
            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        mDropDownList.setOnScrollListener(mScrollListener);

        if (mItemSelectedListener != null) {
            mDropDownList.setOnItemSelectedListener(mItemSelectedListener);
        }

        dropDownView = mDropDownList;

        View hintView = mPromptView;
        if (hintView != null) {
            // if a hint has been specified, we accomodate more space for it and
            // add a text view in the drop down menu, at the bottom of the list
            LinearLayout hintContainer = new LinearLayout(context);
            hintContainer.setOrientation(LinearLayout.VERTICAL);

            LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f);

            switch (mPromptPosition) {
            case POSITION_PROMPT_BELOW:
                hintContainer.addView(dropDownView, hintParams);
                hintContainer.addView(hintView);
                break;

            case POSITION_PROMPT_ABOVE:
                hintContainer.addView(hintView);
                hintContainer.addView(dropDownView, hintParams);
                break;

            default:
                Log.e(TAG, "Invalid hint position " + mPromptPosition);
                break;
            }

            // measure the hint's height to find how much more vertical space
            // we need to add to the drop down's height
            int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST);
            int heightSpec = MeasureSpec.UNSPECIFIED;
            hintView.measure(widthSpec, heightSpec);

            hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams();
            otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin;

            dropDownView = hintContainer;
        }

        mPopup.setContentView(dropDownView);

    } else {
        final View view = mPromptView;
        if (view != null) {
            LinearLayout.LayoutParams hintParams = (LinearLayout.LayoutParams) view.getLayoutParams();
            otherHeights = view.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin;
        }
    }

    // getMaxAvailableHeight() subtracts the padding, so we put it back
    // to get the available height for the whole window
    int padding = 0;
    Drawable background = mPopup.getBackground();
    if (background != null) {
        background.getPadding(mTempRect);
        padding = mTempRect.top + mTempRect.bottom;

        // If we don't have an explicit vertical offset, determine one from the window
        // background so that content will line up.
        if (!mDropDownVerticalOffsetSet) {
            mDropDownVerticalOffset = -mTempRect.top;
        }
    } else {
        mTempRect.setEmpty();
    }

    // Max height available on the screen for a popup.
    boolean ignoreBottomDecorations = mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED;
    final int maxHeight = mPopup.getMaxAvailableHeight(getAnchorView(),
            mDropDownVerticalOffset /*, ignoreBottomDecorations*/);

    if (mDropDownAlwaysVisible || mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) {
        return maxHeight + padding;
    }

    final int childWidthSpec;
    switch (mDropDownWidth) {
    case ViewGroup.LayoutParams.WRAP_CONTENT:
        childWidthSpec = MeasureSpec.makeMeasureSpec(
                mContext.getResources().getDisplayMetrics().widthPixels - (mTempRect.left + mTempRect.right),
                MeasureSpec.AT_MOST);
        break;
    case ViewGroup.LayoutParams.MATCH_PARENT:
        childWidthSpec = MeasureSpec.makeMeasureSpec(
                mContext.getResources().getDisplayMetrics().widthPixels - (mTempRect.left + mTempRect.right),
                MeasureSpec.EXACTLY);
        break;
    default:
        childWidthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.EXACTLY);
        break;
    }

    final int listContent = mDropDownList.measureHeightOfChildrenCompat(childWidthSpec, 0,
            DropDownListView.NO_POSITION, maxHeight - otherHeights, -1);
    // add padding only if the list has items in it, that way we don't show
    // the popup if it is not needed
    if (listContent > 0)
        otherHeights += padding;

    return listContent + otherHeights;
}