Java TextView.setWidth在没有文本时不工作
我动态地将文本视图添加到LinearLayout,并适当地设置它们的布局参数。LinearLayout位于自定义滚动视图中 我没有立即为每个TextView设置文本,因此其中一些在不同的时间设置,而一些则从未设置。我希望它们的宽度都相同,所以我必须等到Java TextView.setWidth在没有文本时不工作,java,android,android-layout,scrollview,android-scrollview,Java,Android,Android Layout,Scrollview,Android Scrollview,我动态地将文本视图添加到LinearLayout,并适当地设置它们的布局参数。LinearLayout位于自定义滚动视图中 我没有立即为每个TextView设置文本,因此其中一些在不同的时间设置,而一些则从未设置。我希望它们的宽度都相同,所以我必须等到onLayout更新它们的宽度(每个文本视图的宽度应该是滚动视图的1/2) 我的问题是:只显示带有文本的文本视图。如果文本为null或空,则它们不会显示,即使我在onLayout中设置了它们的宽度 添加文本视图: //This happens wh
onLayout
更新它们的宽度(每个文本视图的宽度应该是滚动视图的1/2)
我的问题是:只显示带有文本的文本视图。如果文本为null或空,则它们不会显示,即使我在onLayout
中设置了它们的宽度
添加文本视图:
//This happens when scrollView is created. We don't have the scrollview's width yet
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
/**add layout rules omitted **/
linearLayout.addView(textView);
然后设置其宽度:
@Override
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int width = getWidth();
int totalWidth = 0;
for (int i = 0; i < linearLayout.getChildCount(); i++) {
TextView textView = linearLayout.getChildAt(i);
//Each textView will be 1/2 the width of the scrollview
textView.getLayoutParams().width = width / 2;//Try setting params width
textView.setWidth(width / 2);//Try directly setting width
totalWidth += width / 2;
}
linearLayout.getLayoutParams().width = totalWidth;
linearLayout.setMinimumWidth(totalWidth);
linearLayout.requestLayout();
@覆盖
仅限受保护的空心布局(布尔值已更改、整数左侧、整数顶部、整数右侧、整数底部){
超级。仅限布局(已更改、左、上、右、下);
int width=getWidth();
int totalWidth=0;
对于(int i=0;i
注意:我试着用上面两种不同的方法设置它们的宽度,但没有效果。如果文本视图没有文本,它们是否没有宽度?您需要在子文本视图之前调整LinearLayout的大小 首先计算总宽度,将其应用于父布局,然后将一半宽度应用于每个TextView 我也看不到
currentWidth
,所以我自己也没有添加完整的代码
编辑:
linearLayout.getLayoutParams().width = totalWidth = width * 0.5 * linearLayout.getChildCount();
linearLayout.setMinimumWidth(totalWidth);
for (int i = 0; i < linearLayout.getChildCount(); i++) {
TextView textView = linearLayout.getChildAt(i);
textView.setText(""); // I don't think this is needed, but you CAN add this too
//Each textView will be 1/2 the width of the scrollview
textView.getLayoutParams().width = width / 2;//Try setting params width
textView.setWidth(width / 2);//Try directly setting width
}
linearLayout.requestLayout();
linearLayout.getLayoutParams().width=totalWidth=width*0.5*linearLayout.getChildCount();
线性布局。设置最小宽度(总宽度);
对于(int i=0;i
什么是字段?我在任何地方都没有看到它被声明。它是textView,对不起,我刚刚更新了它“将其应用到父布局”是什么意思?不幸的是,这不起作用。和以前一样的问题。你能记录或查看所有的父布局,即线性布局和上面的布局是否有一些宽度大于你试图设置的宽度吗?是的,我正在记录,所有的宽度都是正确的,它们只是因为某种原因而不渲染。我已经缩小了范围,实际上是线性布局的问题由于某些原因,它的宽度没有正确渲染,即使我设置了它。日志显示它设置为正确的值。没有任何意义。