Android 将布局高度设置为Wrapcontent以动态创建textview
我以编程方式创建了LinearLayout,如下所示Android 将布局高度设置为Wrapcontent以动态创建textview,android,textview,Android,Textview,我以编程方式创建了LinearLayout,如下所示 LinearLayout wrapper = new LinearLayout(this.getContext()); 文本视图为TextView et=newtextview(getContext()) 我希望TextView布局高度为wrapcontent,所以我这样做了 et.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTEN
LinearLayout wrapper = new LinearLayout(this.getContext());
文本视图为TextView et=newtextview(getContext())代码>
我希望TextView布局高度为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将高度作为匹配父对象
如何将textviews layouthweight设置为WRAP\u CONTENT
?试试这个
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);
还必须将父线性布局添加到主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);
您是否尝试过在其中设置文本。我认为它会消失,因为它没有显示。我设置了文本,如果我没有为textview设置layoutparams,我的文本是可见的。您是否在活动中设置了任何setcontentview:)@Mario您是否使用了setcontentview(first\u lay)
或将first\u lay
添加到其他xml视图中