我有一个活动,我希望在其中显示包含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);
除了上述2行之外,不使用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布局)? 感谢
答案 0 :(得分:3)
试试这个..
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);
}
}