下面是我的代码和图片。我在 onpostexecute()
中使用 runOnUIThread()
中的数组列表填充 ListView ,它具有从 doInBackground() 中的远程服务器获取的值。但问题是元素只有在焦点位于特定项目上时才可见。我一直在尝试用不同的方法来设置元素可见,但都没有成功。有人可以建议我如何让元素可见吗?注意:我无法扩展 ListActivity,因为我有另一个类需要扩展,它是 Activity 的子类。
runOnUiThread(new Runnable() {
public void run() {
//Updating parsed json data to Listview
ListView listView = (ListView)findViewById(R.id.listsubcategory);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, subCategoryList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selectedSubcategory = subCategoryList.get(position);
Toast.makeText(getApplicationContext(), "You clicked on "+selectedSubcategory, Toast.LENGTH_SHORT).show();
}
});
}
});
最佳答案
问题是列表项的样式。在正常状态下,您的项目具有白色背景和白色文本颜色,因此您看不到它们。当状态变为聚焦时,颜色会发生变化。您可以使用自定义列表项代替系统的 android.R.layout.simple_list_item_1
轻松解决问题。
为项目定义一个布局,它可以是这样的:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/my_item_background"
android:textColor="@color/my_text_color"
/>
现在,如果项目的布局是 res/layout/my_list_item.xml
,则以这种方式创建适配器:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),
R.layout.my_list_item, subCategoryList);
关于android - ListView 元素默认不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14041616/