【发布时间】:2016-06-05 05:22:30
【问题描述】:
作为一个平台上的新手,我在使用 Android 时遇到了困难,据我所知,很多人也是如此。我不知道到目前为止我损失了多少小时——即使数一数也很可怕。
单击按钮后,我基本上想向 LinearLayout 添加一个新的 TextView(或任何其他视图)。这是这部分代码:
public void btnClick(View view) {
final LinearLayout ll = (LinearLayout) findViewById(R.id.test_story_screen_layout);
//checking if child is being added - it is, this value is increase with every button click
android.util.Log.d("child: ", Integer.toString(ll.getChildCount()));
android.util.Log.d("height: ", Integer.toString(ll.getMeasuredHeight()));
ll.post(new Runnable() {
public void run() {
final TextView tv = new TextView(MainActivity.this);
tv.setText("new one " + (new Random()).nextInt());
tv.setTextColor(Color.YELLOW);
LayoutParams lp = new LayoutParams(200, 500);
tv.setLayoutParams(lp);
tv.setVisibility(View.VISIBLE);
ll.addView(tv, ll.getChildCount());
//checking if the run() is called - it is
ll.setBackgroundColor(Color.GREEN);
}
});
ll.requestLayout(); //invalidate() and postInvalidate() also not working
}
但是新添加的View是不可见的(而是作为子添加到LinearLayout中的)。
经过几个小时检查出了什么问题,我才发现当我替换这一行时:
ll.addView(tv, ll.getChildCount());
用这个:
ll.addView(tv, ll.getChildCount() - 1);
然后新视图是可见的,但它会替换前一个视图 - 这是不希望的。
我已经检查了一些解决方案,例如:Refreshing a LinearLayout after adding a view
他们没有帮助我解决这个问题。
更新:
使用 XML 中预定义的两个视图(如下面的代码),线性布局看起来很好。这是 XML 的有趣部分:
<LinearLayout
android:id="@+id/test_story_screen_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_margin="16dp" >
<ImageView
android:id="@+id/imageView1"
android:src="@drawable/example"
android:layout_width="16dp"
android:layout_height="16dp" />
<TextView
android:id="@+id/textView1"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
我认为没有什么不寻常的。所以这两个视图(图像和文本)当然是可见的。然后,我动态添加到此 LinearLayout 的任何新 TextView(通过上面代码中的 btnClick() )都不可见,但它确实被添加到 Layout 中,因为每次子视图时 ll.getChildCount() 都会增加添加(= 单击按钮)。
为了进一步测试,我在 btnClick() 方法的末尾添加了这两行:
android.util.Log.d("tv.getMeasuredWidth: ", Integer.toString(tv.getMeasuredWidth()));
android.util.Log.d("tv.getMeasuredHeight: ", Integer.toString(tv.getMeasuredHeight()));
我猜问题出在 tv (TextView) 而不是 ll (LinearLayout),因为 tv 的宽度和高度均为 0。
【问题讨论】:
-
yes ll.post() 在这里没有任何意义,因为您将视图添加到 onClick 事件侦听器中,这意味着视图已经呈现
-
顺便说一句,线性布局是否设置为 wrap_content?
-
请分享 test_story_screen_layout xml
-
@Bhargav thx,我只是不知道该怎么做,所以我开始检查任何东西,甚至是 post()。 linearlayout 将高度设置为 match_parent 并手动设置宽度
-
是的,您需要将线性布局包装内容理想地包含在滚动视图中