默认情况下,ListView元素不可见

时间:2012-12-26 13:57:56

标签: android android-listview

以下是我的代码和图片。我正在使用runOnUIThread()onpostexecute()中的arraylist填充listview,其中包含从doInBackground()中的远程服务器获取的值。但是,只有当焦点集中在特定项目上时才能看到元素。我一直在尝试使用不同的东西来设置元素可见,但所有这些都是徒劳的。有人可以建议我如何让项目可见。注意:我无法扩展ListActivity,因为我有另一个需要扩展的类,它是一个活动的子类。

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();


                                        }
                                });


                 }
             });

enter image description here

1 个答案:

答案 0 :(得分:5)

问题是列表项的样式。在正常状态下,您的项目具有白色背景和白色文本颜色,因此您无法看到它们。当状态变为聚焦时,颜色会发生变化。您可以使用自定义列表项而不是系统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);
相关问题