【发布时间】:2025-12-02 12:10:02
【问题描述】:
我在 Android Studio 中尝试实现自定义 ListView。我创建了一个名为“custom_layout_rachel.xml”的 xml 文件,并将其放在我的“布局”文件夹中。此文件包含我希望我的 ListView 外观的代码。
我正在尝试使我的页面中名为“activity_urgent__important.xml”的列表视图看起来像“custom_layout_rachel.xml”中的列表视图。在这个文件中,我有以下代码:
<ListView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/lvItems"
tools:listitem="@layout/custom_layout_rachel"
/>
在 Android Studio 中,自定义布局显示出来了,但是当我在我的模拟器上运行应用程序时,它不存在。
这个活动的java代码,如下所示:
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.custom_layout_rachel, items);
lvItems.setAdapter(itemsAdapter);
第三行是我的错误所在。
有谁知道我为什么不能这样做或为什么会出错?
谢谢!!!
新:
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
readItems();
itemsAdapter = new CustomListAdapter(this, items);
lvItems.setAdapter(itemsAdapter);
在“自定义列表适配器(this, items)”上出现错误
我没有适配器代码,但我确实启动了以下,如果它可以工作,我可以实现它:
public class CustomListAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List<String> items ;
public CustomListAdapter(Context context, int textViewResourceId , List<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
public CustomListAdapter(Context context , List<String> list) {
super(context, items);
}
@Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position));
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
【问题讨论】:
-
我们在说什么错误?
-
将 custom_layout_rachel 内的 textview 的 id 更改为 android:id="@android:id/text1"
-
@rachel 如果您想将自定义列表视图与 BaseAdapter 一起使用,请检查这些答案中的代码 sn-p *.com/a/28104066/1140237 *.com/a/28038963/1140237 仅适用于列表视图和 BaseAdapter
标签: java android xml listview android-listview