将视图添加到代码中现有的 xml 视图组
我希望能够在代码中向现有的 xml 布局添加视图:
LinearLayout ll = (LinearLayout) findViewById(R.layout.common_list);
TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setText("sample text");
ll.addView(tv);
setContentView(ll);
在代码中创建新的 LinearLayout 时,它可以工作,但是当使用上面代码中的资源时,它就不行。
common_list.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Quick List"/>
</LinearLayout>
I would like to be able to add a view to an already existing xml layout in code:
LinearLayout ll = (LinearLayout) findViewById(R.layout.common_list);
TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setText("sample text");
ll.addView(tv);
setContentView(ll);
When creating a new LinearLayout in code it works, but when using a Resource like in the code above it doesn’t.
common_list.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Quick List"/>
</LinearLayout>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 LayoutInflater
如果这不起作用,请添加来自 Logcat 的错误。
另外,您应该将 common_list.xml 中 LinearLayout 的属性从 android:layout_width="fill_parent" 更改为 android:layout_width="wrap_content" ,并对 common_list.xml 中的 TextView 执行相同的操作,
为什么?因为您的布局是水平方向的并且它填充了整个屏幕空间。您的 TextEdit 填充的空间与您的布局一样多(因此在本例中它是整个屏幕空间)。现在,当您添加另一个 TextView 时,它会正确添加到第一个 TextEdit 的右侧,因此就像在屏幕外一样。为了准确理解发生了什么:
我也多次遇到过这个问题。通常,如果您将视图添加到布局中并且看不到它(并且没有错误),则问题出在宽度/高度或位置(例如,当您使用relativelayout时)。
Try to use LayoutInflater
If this won't work, please add error from Logcat.
Also, you should change properties from android:layout_width="fill_parent" to android:layout_width="wrap_content" in yout LinearLayout in common_list.xml and also do the same thing to your TextView in common_list.xml
Why? Because your layout is horizontal-oriented and it fills whole screen space. Your TextEdit fills as much space as your layout does (so in this case it's whole screen space). Now, when you add another TextView it is adding properly - to right of your first TextEdit, so it's like out of screen. To understand exactly what happens:
I also had this problem many times. Usually if you add View to layout and you don't see it (and you get no errors) problem is with width/heigth or position (ex. when you use RelativeLayout).