android ListView 及adapterView的使用

ListView是android常用的组件之一,经常会在滑动侧边栏,商品列表等。使用ListView一般有以下5种方式

  • 使用资源数组
  • 使用ArrayAdapter
  • 使用SimpleAdapter
  • 继承BaseAdapter
  • 继承ListActivity

一.使用资源数组

这种方式非常简单,但是显示比较单一,只适合简单的业务需求。

使用方法:

1.在资源文件中定义数组

<resources>
    <array name="main_array">
        <item>基于数组</item>
        <item>ArrayAdapter 方式</item>
        <item>SimpleAdapter 方式</item>
        <item>BaseAdapter 方式</item>
    </array>
</resources>

2.在布局文件中创建ListView标签,并使用entries属性引入数组

<ListView
        android:id="@+id/main_listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/main_array">

    </ListView>

3.绑定点击事件

mainListView = (ListView) findViewById(R.id.main_listView);
        final String[] array = getResources().getStringArray(R.array.main_array);
        mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {//设置点击触发方法
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0 :
                        Toast.makeText(getApplication(),"当前页面便是使用数组生成的ListView",Toast.LENGTH_SHORT).show();
                        break;
                    case 1 :
                        startActivity(new Intent(getApplicationContext(), ArrayAdapterTest.class));//打开新的activity
                        break;
                    case 2 :
                        startActivity(new Intent(getApplicationContext(), SimpleAdapterTest.class));//打开新的activity
                        break;
                    case 3 :
                        startActivity(new Intent(getApplicationContext(), BaseAdapterTest.class));//打开新的activity
                        break;
                }
            }
        });

 二.使用ArrayAdapter

用户需定义item显示布局

使用方法:

1.创建ListView标签

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.xinxin.adaptertest.ArrayAdapterTest">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/array_adapter_h1"
        android:layout_margin="10dp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="绿色分割线"
        android:layout_margin="10dp"
        />
<!-- 显示普通列表 -->
    <ListView
        android:id="@+id/arrayAdapterTestListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#0f0"
        android:dividerHeight="2px"
        android:headerDividersEnabled="false"
        android:layout_margin="10dp"
        >
    </ListView>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="红色分割线"
        android:layout_margin="10dp"
        />
<!-- 显示带checkbox的列表 -->
    <ListView
        android:id="@+id/arrayAdapterTestListView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#ff3f1d"
        android:dividerHeight="2px"
        android:headerDividersEnabled="false"
        android:layout_margin="10dp"
        >
    </ListView>
</LinearLayout>

2.创建显示item布局

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:textSize="25sp">

</TextView>

3.activity代码

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_array_adapter_test);
        listView = (ListView) findViewById(R.id.arrayAdapterTestListView);
        listView1 = (ListView) findViewById(R.id.arrayAdapterTestListView1);
        List<String> list = new ArrayList<String>();
        for(int i=0; i<5; i++){
            list.add("green:item"+i);
        }
        //创建ArrayAdapter实例
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.array_adapter_test_item, list);
        //为ListView添加adapter
        listView.setAdapter(arrayAdapter);
        //为每个元素绑定点击方法
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println(position);
                TextView tv = (TextView) view;
                Toast.makeText(getApplication(), "您点击了:" + tv.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });
        //为每个元素绑定选择方法
        listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                Toast.makeText(getApplication(), "您选择了:"+tv.getText().toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        list = new ArrayList<String>();
        for(int i=0; i<5; i++){
            list.add("red:item"+i);
        }

        arrayAdapter = new ArrayAdapter<String>(this, R.layout.select_dialog_multichoice_material, list);//设置多选列表,使用android自带布局

        listView1.setAdapter(arrayAdapter);

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//处理checkbox勾选
                CheckedTextView checkedTextView = (CheckedTextView) view;
                if(checkedTextView.isChecked()){
                    checkedTextView.setChecked(false);
                }else{
                    checkedTextView.setChecked(true);
                }
            }
        });

    }

三.使用SimpleAdapter

评价最多的一句话“简单而不简单”,使用SimpleAdapter可以创建自定义的显示方式

使用方法:

1.定义布局,只需在主布局中放入一个简单的ListView

<ListView
        android:id="@+id/simpleAdapterListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">

    </ListView>

2.定义item显示布局,注意logoImage,name, desc这三个控件,在第三步中会使用到。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_margin="10dp">

    <ImageView
        android:id="@+id/logoImage"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="10dp"/>

    <TextView
        android:id="@+id/desc"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="10dp"/>
</LinearLayout>

 

 

3.activity代码

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_adapter);
        listView = (ListView) findViewById(R.id.simpleAdapterListView);

        int[] logoIds = new int[]{R.drawable.p1, R.drawable.p2};
        String[] names = new String[]{"元素1", "元素2"};
        String[] descs = new String[]{"这是测试元素1","这是测试元素2"};
        List<Map<String, Object>> list =  new ArrayList<Map<String, Object>>();
        for (int i=0; i<2; i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("logoImage", logoIds[i]);
            map.put("name", names[i]);
            map.put("desc", descs[i]);
            list.add(map);
        }

        //实例化SimpleAdapter
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.activity_simple_adapter_item
                , new String[]{"logoImage","name","desc"}, new int[]{R.id.logoImage, R.id.name, R.id.desc});

        listView.setAdapter(simpleAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LinearLayout line = (LinearLayout) view;
                TextView textView = (TextView) line.getChildAt(1);
                Toast.makeText(getApplication(), "您点击了:"+textView.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });

    }

 

四.BaseAdapter

需要继承BaseAdapter,并实现抽象方法,用户可以高度控制。

使用方法:

1.在主布局中创建ListView

<ListView
        android:id="@+id/baseAdapterListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        ></ListView>

2.编写activity代码

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_adapter_test);
        listView = (ListView) findViewById(R.id.baseAdapterListView);
        BaseAdapter baseAdapter = new BaseAdapter() {//继承BaseAdapter,并实现抽象方法
            @Override
            public int getCount() {//元素个数
                return 10;
            }
            @Override
            public Object getItem(int position) {
                return null;
            }
            @Override
            public long getItemId(int position) {
                return position;
            }
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LinearLayout linearLayout = new LinearLayout(BaseAdapterTest.this);//创建线性布局
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                ImageView imageView = new ImageView(BaseAdapterTest.this);//创建图片布局
                imageView.setImageResource(R.drawable.p1);
                linearLayout.addView(imageView);
                TextView textView = new TextView(BaseAdapterTest.this);//常见TextView布局
                textView.setText("item"+position);
                linearLayout.addView(textView);
                return linearLayout;
            }
        };
        listView.setAdapter(baseAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {//处理点击事件
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LinearLayout linearLayout  = (LinearLayout) view;
                TextView textView = (TextView) linearLayout.getChildAt(1);
                Toast.makeText(getApplication(), "您点击了:"+textView.getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }

5. 继承ListActivity类似于ArrayAdapter,这里便不再介绍。

 

最后将效果图发上来:

 

android ListView 及adapterView的使用
滚动到顶部