Show last item in ListiView when you click on edit text

前端 未结 4 490
臣服心动
臣服心动 2021-01-01 01:07

currently I\'m doing this to get the focus of the last item in a listview after clicking on an edit text:

    bodyText.setOnFocusChangeListener(new OnFocusCh         


        
相关标签:
4条回答
  • 2021-01-01 01:12

    For Someone who works with new RecyclerView widget that is recommended:

    just like accepted answer but replace:

    setSelection(getCount());
    

    with this:

     (LinearLayoutManager)getLayoutManager())
    .scrollToPositionWithOffset(getAdapter().getItemCount() - 1, 0);
    

    just LinearLayoutManagerand StaggeredGridLayoutManager have this method. so use this LayoutManagers.

    0 讨论(0)
  • 2021-01-01 01:19

    I made my own Custom ListView like this:

    public class CustomListView extends ListView {
    
    public CustomListView (Context context) {
        super(context);
    }
    
    public CustomListView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public CustomListView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    @Override
    protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
        super.onSizeChanged(xNew, yNew, xOld, yOld);
    
        setSelection(getCount());
    
    }
    }
    

    You must include all 3 constructors or an exception will be thrown.

    Then in the XML where you usually put

    ListView

    android:id="@+id/android:list"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    

    Change ListView to com.blah.blah.CustomListView.

    Sorry for the messy layout, for some reason I can't get the formatter to properly work.

    Run your application. Now when you click on the EditText, it shows the last item AFTER the soft keyboard shows! Note that there are some limitations like when the auto-complete function appears when you type text in the EditText, it will show the last item as well due to a change in size of the ListView.

    Enjoy!

    0 讨论(0)
  • 2021-01-01 01:26

    The solution offered by @Maurice is almost correct (or at least it almost works for me). I had to modify the onSizeChanged method to put the setSelection into a call to post, as follows:

    @Override
    protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
        super.onSizeChanged(xNew, yNew, xOld, yOld);
    
        post(new Runnable() {
            public void run() {
                setSelection(getCount());
            }
        });
    }
    

    Per the docs, post "Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread." This is also a technique used in some of the Android AbsListView source.

    0 讨论(0)
  • 2021-01-01 01:34

    Use

    <activity
    .....
    android:windowSoftInputMode="adjustResize" />
    

    in your manifest file.

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