ListView 使用(1)

来源:互联网 发布:一叶而知四季 编辑:程序博客网 时间:2024/05/17 01:53

ListView 使用(1)

参考:

ListView:https://developer.android.com/reference/android/widget/ListView.html
列表视图:https://developer.android.com/guide/topics/ui/layout/listview.html


实现功能:

  1. 最简单的列表展示;
  2. 自定义布局展示(每行有一个图片外加一个文本);
  3. 增减列表;
  4. 点击列表,获取该列表的位置以及内容;
  5. 动态修改列表中的内容(点击列表,该列中的内容发生变化);

适配器使用:

ArrayAdapter


最简单的文本展示(每行单个文本)

只需要在 xml 文件中加入列表组件,同时在 activity 中设置适配器即可

新建 OneActivity.java

package com.uniview.listdemo.one;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.ListViewCompat;import android.widget.ArrayAdapter;import android.widget.ListAdapter;import android.widget.ListView;import com.uniview.listdemo.R;public class OneActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_one);        ListView listView = (ListView)findViewById(R.id.ao_lv);        String[] arr = getResources().getStringArray(android.R.array.phoneTypes);        ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arr);        listView.setAdapter(adapter);    }}

新建 activity_one.xml

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.uniview.listdemo.one.OneActivity">    <ListView        android:id="@+id/ao_lv"        android:layout_width="match_parent"        android:layout_height="match_parent" /></android.support.constraint.ConstraintLayout>

自定义布局展示(每行有一个图片外加一个文本)

此时需要自定义每行的布局文件,通过适配器将数据写入 ListView

新建 ItemTwo.java

package com.uniview.listdemo.two;/** * Created by Lenovo on 2017/3/4. */public class ItemTwo {    int id;    String text;    public ItemTwo(int id, String text) {        this.id = id;        this.text = text;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getText() {        return text;    }    public void setText(String text) {        this.text = text;    }    @Override    public String toString() {        return "ItemTwo{" +                "id=" + id +                ", text='" + text + '\'' +                '}';    }}

新建 item_two.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:padding="16dp">    <ImageView        android:id="@+id/it_iv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@mipmap/ic_launcher" />    <TextView        android:id="@+id/it_tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:text="@string/app_name"        android:textSize="32dp" /></RelativeLayout>

新建 TwoAdapter.java

package com.uniview.listdemo.two;import android.content.Context;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import com.uniview.listdemo.R;import java.util.List;import java.util.zip.Inflater;/** * Created by Lenovo on 2017/3/4. */public class TwoAdapter extends ArrayAdapter<ItemTwo> {    private Context context;    private int resourceId;    public TwoAdapter(Context context, int resourceId, List<ItemTwo> itemTwoList) {        super(context, resourceId, itemTwoList);        this.context = context;        this.resourceId = resourceId;    }    @NonNull    @Override    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {//        return super.getView(position, convertView, parent);        ItemTwo itemTwo = getItem(position);        View view;        ViewHolder viewHolder;        if (convertView == null) {            view = LayoutInflater.from(context).inflate(resourceId, null);            viewHolder = new ViewHolder();            viewHolder.iv = (ImageView)view.findViewById(R.id.it_iv);            viewHolder.tv = (TextView)view.findViewById(R.id.it_tv);            view.setTag(viewHolder);        } else {            view = convertView;            viewHolder = (ViewHolder)view.getTag();        }        viewHolder.iv.setImageResource(itemTwo.getId());        viewHolder.tv.setText(itemTwo.getText());        return view;    }    class ViewHolder {        ImageView iv;        TextView tv;    }}

新建 TwoActivity.java

package com.uniview.listdemo.two;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.ListViewCompat;import android.widget.ListView;import com.uniview.listdemo.R;import java.util.ArrayList;import java.util.List;public class TwoActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_two);        ListView listView = (ListView)findViewById(R.id.at_lv);        List<ItemTwo> itemTwoList = getItemTwo();        TwoAdapter adapter = new TwoAdapter(this, R.layout.item_two, itemTwoList);        listView.setAdapter(adapter);    }    private List<ItemTwo> getItemTwo() {        List<ItemTwo> itemTwoList = new ArrayList<>();        String[] arr = getResources().getStringArray(android.R.array.phoneTypes);        for (String str : arr) {            ItemTwo itemTwo = new ItemTwo(R.mipmap.ic_launcher, str);            itemTwoList.add(itemTwo);        }        return itemTwoList;    }}

新建 activity_two.xml

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.uniview.listdemo.two.TwoActivity">    <ListView        android:id="@+id/at_lv"        android:layout_width="match_parent"        android:layout_height="match_parent" /></android.support.constraint.ConstraintLayout>

首先需要继承 ArrayAdapter<T> 类,同时重写其 getView 函数

View getView(int position, View convertView, ViewGroup parent)
  • 参数 position:适配器数据集中对应的位置;
  • 参数 convertView:如果不为空,可以直接重用;否则,新建一个 view
  • 参数 parent:父视图

返回:填充了对应数据的视图


增减列表

在构建完一个 ListView 后,可能需要动态的改变数据,或者从末尾增减,或者从中间插入删除

当前使用 ArrayAdapter<T> 来作为适配器,这个类也提供了以下函数来进行动态处理

添加数据(addaddAllinsert

使用函数 add 可以从末尾增加数据项:

    /**     * Adds the specified object at the end of the array.     *     * @param object The object to add at the end of the array.     */    public void add(@Nullable T object) {        synchronized (mLock) {            if (mOriginalValues != null) {                mOriginalValues.add(object);            } else {                mObjects.add(object);            }        }        if (mNotifyOnChange) notifyDataSetChanged();    }

也可以使用 addAll 函数添加多个数据项:

/** * Adds the specified Collection at the end of the array. * * @param collection The Collection to add at the end of the array. * @throws UnsupportedOperationException if the <tt>addAll</tt> operation *         is not supported by this list * @throws ClassCastException if the class of an element of the specified *         collection prevents it from being added to this list * @throws NullPointerException if the specified collection contains one *         or more null elements and this list does not permit null *         elements, or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the *         specified collection prevents it from being added to this list */public void addAll(@NonNull Collection<? extends T> collection) {    synchronized (mLock) {        if (mOriginalValues != null) {            mOriginalValues.addAll(collection);        } else {            mObjects.addAll(collection);        }    }    if (mNotifyOnChange) notifyDataSetChanged();}/** * Adds the specified items at the end of the array. * * @param items The items to add at the end of the array. */public void addAll(T ... items) {    synchronized (mLock) {        if (mOriginalValues != null) {            Collections.addAll(mOriginalValues, items);        } else {            Collections.addAll(mObjects, items);        }    }    if (mNotifyOnChange) notifyDataSetChanged();}

上面两个函数都是在末尾进行数据的添加,使用 insert 可以从中间来进行数据的添加:

/** * Inserts the specified object at the specified index in the array. * * @param object The object to insert into the array. * @param index The index at which the object must be inserted. */public void insert(@Nullable T object, int index) {    synchronized (mLock) {        if (mOriginalValues != null) {            mOriginalValues.add(index, object);        } else {            mObjects.add(index, object);        }    }    if (mNotifyOnChange) notifyDataSetChanged();}

注:需要指明添加的下标,从0开始

移除数据(removeclear

使用函数 remove 可以移除指定对象:

/** * Removes the specified object from the array. * * @param object The object to remove. */public void remove(@Nullable T object) {    synchronized (mLock) {        if (mOriginalValues != null) {            mOriginalValues.remove(object);        } else {            mObjects.remove(object);        }    }    if (mNotifyOnChange) notifyDataSetChanged();}

使用函数 clear 可以清空所有的数据:

/** * Remove all elements from the list. */public void clear() {    synchronized (mLock) {        if (mOriginalValues != null) {            mOriginalValues.clear();        } else {            mObjects.clear();        }    }    if (mNotifyOnChange) notifyDataSetChanged();}

下面举一个增减列表的例子:设置两个按钮, add 按钮可以从最开始增加数据,delete 按钮可以从末尾移除数据

新建 activity_three.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.uniview.listdemo.three.ThreeActivity">    <ListView        android:id="@+id/at_lv"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        tools:layout_editor_absoluteX="8dp"        tools:layout_editor_absoluteY="0dp">        <Button            android:id="@+id/btn_add"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="add" />        <Button            android:id="@+id/btn_delete"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="delete" />    </LinearLayout></LinearLayout>

新建 ThreeActivity.java

package com.uniview.listdemo.three;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ListView;import com.uniview.listdemo.R;import com.uniview.listdemo.two.ItemTwo;import java.util.ArrayList;import java.util.List;public class ThreeActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_three);        ListView listView = (ListView)findViewById(R.id.at_lv);        List<ItemTwo> itemTwoList = getItemTwo();        final ThreeAdapter adapter = new ThreeAdapter(this, R.layout.item_two, itemTwoList);        listView.setAdapter(adapter);        Button btnAdd = (Button)findViewById(R.id.btn_add);        btnAdd.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                adapter.addItem(new ItemTwo(R.mipmap.ic_launcher, "add"));            }        });        Button btnDelete = (Button)findViewById(R.id.btn_delete);        btnDelete.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                adapter.removeItem();            }        });    }    private List<ItemTwo> getItemTwo() {        List<ItemTwo> itemTwoList = new ArrayList<>();        String[] arr = getResources().getStringArray(android.R.array.phoneTypes);        for (String str : arr) {            ItemTwo itemTwo = new ItemTwo(R.mipmap.ic_launcher, str);            itemTwoList.add(itemTwo);        }        return itemTwoList;    }}

新建 ThreeAdapter.java

package com.uniview.listdemo.three;import android.content.Context;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import com.uniview.listdemo.R;import com.uniview.listdemo.two.ItemTwo;import java.util.List;/** * Created by Lenovo on 2017/3/5. */public class ThreeAdapter extends ArrayAdapter<ItemTwo> {    private Context context;    private int resourceId;    public ThreeAdapter(Context context, int resourceId, List<ItemTwo> itemTwoList) {        super(context, resourceId, itemTwoList);        this.context = context;        this.resourceId = resourceId;    }    @NonNull    @Override    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {//        return super.getView(position, convertView, parent);        ItemTwo itemTwo = getItem(position);        View view;        ViewHolder viewHolder;        if (convertView == null) {            view = LayoutInflater.from(context).inflate(resourceId, null);            viewHolder = new ViewHolder();            viewHolder.iv = (ImageView) view.findViewById(R.id.it_iv);            viewHolder.tv = (TextView) view.findViewById(R.id.it_tv);            view.setTag(viewHolder);        } else {            view = convertView;            viewHolder = (ViewHolder) view.getTag();        }        viewHolder.iv.setImageResource(itemTwo.getId());        viewHolder.tv.setText(itemTwo.getText());        return view;    }    public void addItem(ItemTwo itemTwo) {        insert(itemTwo, 0);    }    public void removeItem() {        remove(getItem(getCount() - 1));    }    class ViewHolder {        ImageView iv;        TextView tv;    }}

效果如下:

这里写图片描述


点击列表,获取该列表的位置以及内容

通过点击事件,可以获取点击行的位置及其内容信息

ThreeAdapter.java 添加以下函数:

...public void clickItem(int position, long id) {    ItemTwo itemTwo = getItem(position);    Toast.makeText(context,            itemTwo.getText() + " index: " + String.valueOf(position) + " id: " + String.valueOf(id),            Toast.LENGTH_SHORT).show();}...

ThreeActivity.java 中添加函数:

@Overrideprotected void onCreate(Bundle savedInstanceState) {    ...    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {        @Override        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {            adapter.clickItem(position, id);        }    });}

使用接口 OnItemClickListener 后即可调用函数 onItemClick

/** * Interface definition for a callback to be invoked when an item in this * AdapterView has been clicked. */public interface OnItemClickListener {    /**     * Callback method to be invoked when an item in this AdapterView has     * been clicked.     * <p>     * Implementers can call getItemAtPosition(position) if they need     * to access the data associated with the selected item.     *     * @param parent The AdapterView where the click happened.     * @param view The view within the AdapterView that was clicked (this     *            will be a view provided by the adapter)     * @param position The position of the view in the adapter.     * @param id The row id of the item that was clicked.     */    void onItemClick(AdapterView<?> parent, View view, int position, long id);}

注:其中第三个参数 position 即是所点击行在数据集中的位置

还有一个接口 OnItemSelectedListener,但是不知道为社么没有用?


动态修改列表中的内容(点击列表,该列中的内容发生变化)

当获取所点击行的数据集后,就可以进行修改,修改完后还需要进行更新

修改函数 clickItem

public void clickItem(int position, long id) {    ItemTwo itemTwo = getItem(position);    Toast.makeText(context,            itemTwo.getText() + " index: " + String.valueOf(position) + " id: " + String.valueOf(id),            Toast.LENGTH_SHORT).show();    itemTwo.setText("Hello zj");    notifyDataSetChanged();}

函数 notifyDataSetChanged() 用于通知 Adapter 更新数据:

结果:

这里写图片描述

0 0
原创粉丝点击