Search code examples
androidandroid-layoutlistadapterandroid-listfragment

replacing android.R.layout.simple_list_item_1 with my own list


i wanna replace my own list instead of android.R.layout.simple_list_item_1 but iam getting the following error 06-15 18:28:29.604: E/AndroidRuntime(3291): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextViewatandroid.widget.ArrayAdapter.createViewFromResource i cant manage to solve it my new list look like this

<?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"/>

and my java class look like this

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


   }

Solution

  • You should pass to the array adapter also the id of the TextView resource where the text should be placed. Replace this line:

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

    with

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