简体   繁体   中英

Custom text view adapter not working on list view

I'm trying to use a custom text view for the items in my list but when deploying my app it doesn't appear.

fragment class

public class FragmentMainList extends android.support.v4.app.Fragment {

    ListView list_main;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_main_list, container, false);

        String[] listContent = {
            getActivity().getResources().getString(R.string.item_0),
            getActivity().getResources().getString(R.string.item_1),
            getActivity().getResources().getString(R.string.item_2)
        };

        list_main = (ListView)v.findViewById(R.id.list_main);
        ArrayAdapter adapter = new ArrayAdapter(getActivity(),R.layout.list_item,listContent);
        list_main.setAdapter(adapter);

        return v;
    }
}

list_item.xml

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

    <TextView
        android:id="@+id/list_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="12dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

I know the line of below has something to do with it, but I don't know what to change it to:

ArrayAdapter adapter = new ArrayAdapter(getActivity(),R.layout.list_item,listContent); list_main.setAdapter(adapter);

您需要将TextView的id添加为ArrayAdapter构造函数调用的参数,例如new ArrayAdapter(getActivity(), R.layout.list_item, R.id.list_item, listContent)

The answer by Martin should work. However, if you remove your parent LinearLayout from the layout file and make the TextView the only View/ViewGroup in the file then it should work. This would be "best" if it is always only going to contain a TextView . If you might want to add other Views to it later, then the answer by Martin may be "better".

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp"
    android:textAppearance="?android:attr/textAppearanceLarge" />

It would be this constructor in the Docs

http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context , int, java.util.List)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM