作为平台上的新手,我在使用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);
这样便可以看到新的视图,但是它将替换上一个视图-这是不希望的。
我已经检查了一些解决方案,例如:在添加视图后刷新LinearLayout
他们没有帮助我解决这个问题。
更新:
使用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>
我认为没什么不寻常的。因此,这两个视图(图像和文本)当然是可见的。然后,我动态地(通过上面的代码中的btnClick())添加到此LinearLayout的任何新TextView都不可见,但实际上已添加到Layout中,因为每次在子视图被添加时ll.getChildCount()都会增加。已添加(=按钮已单击)。
为了进一步测试,我在btnClick()方法的末尾添加了这两行:
android.util.Log.d("tv.getMeasuredWidth: ", Integer.toString(tv.getMeasuredWidth()));
android.util.Log.d("tv.getMeasuredHeight: ", Integer.toString(tv.getMeasuredHeight()));
我猜问题是电视(TextView)而不是ll(LinearLayout),因为电视的宽度和高度都为0。
此Android问题涉及许多相关事项,其中包括:
该死的。我发现Android是我所见识最少的平台之一。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句