【发布时间】:2011-03-27 09:23:08
【问题描述】:
我有一个活动,我想在其中显示一个带有 2 个简单字符串项的 ListView。我尝试了两种不同的方式(w/xml 布局和 w/o xml 布局)-两种方式我都添加了 2 个项目,但最终这些项目仅在创建 w/xml 布局列表的版本中可见。这是为什么呢?
xml 布局,list_view_custom_layout.xml 包含:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/ListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
使用 XML 的代码(并且运行良好)执行以下操作:
activity.setContentView(R.layout.list_view_custom_layout); //this must be done here
listView=(ListView)activity.findViewById(R.id.ListView);
除了上面两行之外,不使用 XML 的代码是相同的 它这样做(这似乎应该是等效的):
LinearLayout customLayout=new LinearLayout(activity);
//customLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
customLayout.setLayoutParams(layout);
ListView listView=new ListView(activity);
customLayout.addView(listView,new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
不是 2 等价物,如果是,为什么要添加项目(通过适配器) 仅显示第一种方法(其中使用 xml 布局)? 谢谢
【问题讨论】:
-
使用 Hierarchy Viewer 检查这两种情况,看看哪里出错了。
标签: android xml listview layout