我有一个活动,在其中我想要显示一个包含2个简单字符串项的ListView。我尝试了两种不同的方式(w/xml布局和w/o xml布局)--这两种方式我都添加了这两个项,但最终这些项只在创建具有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));
这两种方法不是等价的吗?如果是这样,为什么添加的项(通过适配器)只为第一种方法(使用xml布局)显示?谢谢
发布于 2011-08-25 05:48:05
试试这个..。
public class VersionActivity extends Activity {
LinearLayout linearLayout;
ListView listView;
ArrayAdapter<String> aR;
String[] str = new String[] { "item1", "item2", "item3", "item4", "item5",
"item6" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
linearLayout = new LinearLayout(this);
listView = new ListView(this);
aR = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, str);
listView.setAdapter(aR);
linearLayout.addView(listView);
setContentView(linearLayout);
}
}
https://stackoverflow.com/questions/5448308
复制