简体   繁体   中英

Setting Layout Height to Wrapcontent to dynamically created textview

I have created LinearLayout programatically as

LinearLayout wrapper = new LinearLayout(this.getContext());

and TextView as TextView et = new TextView(getContext());

i wanted textviews layout height to be wrapcontent so i did this

et.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

and then i add Textview et to LinearLayout as

wrapper.addView(et);

but when i set LayoutParams as above my textview dissapears and doesn't show in UI. If I remove it by default Textview takes height as MATCHPARENT.

How can i set textviews layoutheight to WRAP_CONTENT ?

Try this..

LinearLayout first_lay = new LinearLayout(this);

LinearLayout.LayoutParams lp_icon = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

first_lay.setOrientation(LinearLayout.VERTICAL);
first_lay.setLayoutParams(lp_icon);

LinearLayout.LayoutParams tests = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER);

TextView text1 = new TextView(this);
text1.setLayoutParams(tests);
text1.setText("Text");
text1.setTextSize(18);

first_lay.addView(text1);

also have to add that parent linear layout into the main contentlayout parent ie it all be visible in side activity view

  LinearLayout child_insidenew_layout = new LinearLayout(getActivity());
                        child_insidenew_layout.setOrientation(LinearLayout.HORIZONTAL);
 LinearLayout.LayoutParams child_inside_paramsnew = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
                        child_insidenew_layout.setLayoutParams(child_inside_paramsnew);
  child_insidenew_layout.setGravity(Gravity.CENTER_VERTICAL);
                        child_insidenew_layout.setBackgroundResource(R.drawable.layout_selector);
TextView textrootname = new TextView(getActivity());
 LinearLayout.LayoutParams TextView_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
  textrootname.setText("here is ur text");
  textrootname.setSingleLine(true);
  textrootname.setGravity(Gravity.CENTER);
  textrootname.setTextColor(Color.BLACK);
  textrootname.setTextSize(15);
  child_insidenew_layout.addView(textrootname, TextView_params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM