将Wrap_content的Layout Height设置为动态创建的textview

时间:2014-04-02 06:13:34

标签: android textview

我以编程方式创建了LinearLayout

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

和TextView为TextView et = new TextView(getContext());

我希望textviews布局高度为wrapcontent,所以我做了这个

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

然后我将Textview et添加到LinearLayout

wrapper.addView(et);

但是当我将LayoutParams设置为上面时,我的textview消失了,并且没有在UI中显示。 如果我默认删除它Textview将高度作为MATCHPARENT。

如何将textviews layoutheight设置为WRAP_CONTENT

2 个答案:

答案 0 :(得分:0)

试试这个..

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);

答案 1 :(得分:0)

还必须将父线性布局添加到主要的contentlayout父级中,即它们在侧面活动视图中都可见

  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);