set focus on any item of listview in android

前端 未结 5 1532
时光取名叫无心
时光取名叫无心 2021-01-02 09:33

I have a listview which contains textviews as its elements.

  1. Now I want the first item of the list to be automatically focused when I launch the application
相关标签:
5条回答
  • 2021-01-02 10:10
    1. Your ListView should be like this:

      <ListView
          android:id="@+id/my_list"
          android:layout_width="wrap_content"
          android:layout_height="200dp"
          android:layout_margin="10dp"
          android:choiceMode="none"
          android:focusable="true"
          android:fadeScrollbars="false">
          <requestFocus />
      </ListView>
      
    2. mListView.setSelection(3); //or any other number

    0 讨论(0)
  • 2021-01-02 10:11

    ListView has a setSelected method that takes the index of the item in the list.

    0 讨论(0)
  • 2021-01-02 10:12

    Setting selection and setting focus are two different things. If you want to just setSelection to some item then you can use below code.

        mListView.setSelection(position);
    

    But this definitely does not mean the Listview is focused.For focussing you have to use

        mListView.requestFocus();
    

    For changing focus on click of a button you can place the code on onClick() of the button.

    0 讨论(0)
  • 2021-01-02 10:20

    for me the problem was solved by

    listView.setItemsCanFocus(true);
    
    0 讨论(0)
  • 2021-01-02 10:25

    I guess I was in the same situation. I wanted to be able to control the focus of the listview programmatically with buttons .

    One solution is to deal with the setFocusableInTouchMode, but I've never achieved to make it work.

    The other solution is to forget about the focus and use a checkable listview. First set your listview to "single choice mode" in XML or in java : Mylistview.setChoiceMode(1)

    Then you'll be able to check any item you want with Mylistview.setItemChecked(position, true)

    So when you lunch the application (OnCreate), use Mylistview.setItemChecked(0, true) to check your first item.

    Then if you want your button to select the next item for exemple, use :

    Mylistview.setItemChecked(Mylistview.getCheckedItemPosition() + 1, true)
    

    You can specify the look when the item is checked or not and there's different pre-built chekable listviews.

    If you want more explanations, see my post

    0 讨论(0)
提交回复
热议问题