用我自己的列表替换android.R.layout.simple_list_item_1

时间:2013-06-15 15:44:35

标签: android android-layout listadapter android-listfragment

我想替换我自己的列表而不是android.R.layout.simple_list_item_1但是我得到以下错误06-15 18:28:29.604:E / AndroidRuntime(3291):java.lang.IllegalStateException:ArrayAdapter需要资源ID为TextView引起:java.lang.ClassCastException:android.widget.RelativeLayout无法强制转换为android.widget.TextViewatandroid.widget.ArrayAdapter.createViewFromResource 我无法设法解决它我的新列表看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:paddingLeft="10dp"
    android:paddingTop="10dp"
    android:textColor="#FFFFFF"
    android:background="@drawable/burger_bg_selector"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<View
    android:id="@+id/view1"
    android:layout_width="wrap_content"
    android:layout_height="1dp"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:background="@drawable/main_list_sep"/>

我的java类看起来像这样

public class MenuFragment extends ListFragment {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(getActivity(),
            R.layout.burger_list, new String[] { " First",  " Second", " Third", " Fourth", " Fifth", " Sixth"}));
    getListView().setCacheColorHint(0);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    ((MenuActivity)getActivity()).getSlideoutHelper().close();
}


   }

2 个答案:

答案 0 :(得分:5)

您应该将应该放置文本的TextView资源的id传递给数组适配器。替换此行:

setListAdapter(new ArrayAdapter<String>(getActivity(),
            R.layout.burger_list, new String[] { " First",  " Second", " Third", " Fourth", " Fifth", " Sixth"}));

setListAdapter(new ArrayAdapter<String>(getActivity(),
            R.layout.burger_list, R.id.textView1, new String[] { " First",  " Second", " Third", " Fourth", " Fifth", " Sixth"}));

答案 1 :(得分:0)

看起来您正在将RelativeLayout而不是TextView转换为ArrayAdapter对象。看不到它,但似乎'R.layout.burger_list'是RelativeLayout的id,而'textView1'是你要投射的textview的实际id。