使用 ListFragment 设置列表视图的第一个检查项

Set first Item checked of listview using ListFragment

我想在创建 activity 时将列表视图的第一项检查设置为默认值。我的 activity 由具有 ListView 的 ListFragment 组成。第一项需要检查。我写了

listView.setItemChecked(0, true);
        listView.setSelection(0);
        listView.setSelected(true); 

以上代码用于检查,但在 activity 创建时未被检查。请告诉我为什么以及如何实现?

完整代码:

public class LeftFilterContents extends ListFragment implements AdapterView.OnItemClickListener {

    Get get;
    View view;
    ListView listView;

    public interface Get {
        void getData(int s);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            get = (Get) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.list_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<String> arrayList = new ArrayList<>();
        listView = (ListView) view.findViewById(android.R.id.list);

        arrayList.add("Type");
        arrayList.add("Date");
        arrayList.add("From to Date");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
        setListAdapter(adapter);
        listView.setItemChecked(0, true);
        listView.setSelection(0);
        listView.setSelected(true);
        getListView().setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
        get.getData(position);
    }

列表视图:

<ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

试试这个

yourListView.setSelection(0);

// updated the code
listView.setItemChecked(0,true)
//yourListView.getSelectedView().setSelected(true);

添加这一行:

adapter.notifyDataSetChanged();
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

所以你将拥有:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),     android.R.layout.simple_list_item_1, arrayList);
setListAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);  
listView.setItemChecked(0, true);
getListView().setOnItemClickListener(this);
adapter.notifyDataSetChanged();