Android ListView setSelection用法

setSelection可以让ListView跳转到某个item显示(无滑动效果)

以下实例代码简单演示了一个ListView,当点击第一个item列表会跳转到最后一个显示

当点击最后一个item列表会跳转到第一个item显示

<?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">
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
public class MainActivity3 extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        final ListView listView = findViewById(R.id.list_view);
        String[] items = new String[100];
        for (int i = 0; i < items.length; i++) {
            items[i] = "item" + i;
        }
        listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    listView.setSelection(parent.getAdapter().getCount() - 1);
                } else if(position == parent.getAdapter().getCount() - 1) {
                    listView.setSelection(0);
                }
            }
        });
    }
}

 

posted @ 2019-09-04 14:28  野猿新一  阅读(92)  评论(0编辑  收藏  举报