[英]Wrapping a LinearLayout around a TextView
我有以下代码,用XML布局文件中的TextView填充ListView。 但是,如果我尝试将LinearLayout包裹在TextView周围,则会崩溃!
码:
setListAdapter(new ArrayAdapter<MyData>(getApplicationContext(), R.layout.articlelist, items));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyData d = items[position];
Bundle bundle = new Bundle();
bundle.putString("theArticleText", d.getText());
Intent newIntent = new Intent(getApplicationContext(), ArticleDetail.class);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
});
工作的XML:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" />
无法使用的XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" />
</LinearLayout>
任何想法为什么会这样??? 我还要做的是在列表中的每个项目旁边添加一个图标,我是否朝着正确的方向前进???
干杯,
麦克风。
如果查看ArrayAdapter的文档,您会发现构造函数将textViewResourceId作为第二个参数,这就是为什么它不会使用第一个xml崩溃的原因。
顺便说一下,请记住,TextView是视图,LinearLayout是ViewGroup。
如果要使用自己的布局,则必须编写一个自定义适配器。
希望对您有所帮助!
如果要使用更复杂的布局,则必须将用于ArrayAdapter的构造函数更改为同时使用布局ID和TextView ID来插入文本的版本。 当您的布局只是一个TextView
,您可以放弃其他版本,因为您只需要引用一件事; 但是现在您必须告诉适配器要膨胀的布局以及要使用的新布局中的哪个视图。
您还需要修改布局,以便TextView具有有效的ID可供参考:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" />
</LinearLayout>
注意TextView
附带的android:id
参数。 然后在您的Java代码中使用以下构造函数:
new ArrayAdapter<MyData>(getApplicationContext(), R.layout.articlelist, R.id.textview, items)
现在,这可以正确地告诉适配器从何处获得字符串数据的放置位置。
高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.