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

时间:2016-10-18 17:48:10

标签: android listview android-listfragment

我想在创建活动时将listview的第一个项目设置为默认值。我的活动包含ListFragment,它有ListView。需要检查第一项。我写了

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

上面的代码用于检查但是在创建的活动上没有检查。请告诉我为什么以及如何实现?

完整代码:

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:

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

2 个答案:

答案 0 :(得分:0)

试试这个

yourListView.setSelection(0);

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

答案 1 :(得分:-1)

添加以下行:

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