Android knowledge points - the use of ListView

Use of ListView

1. Easy to use

Steps for usage

1. Add the ListView control to the layout file

<ListView
        android:id="@+id/v_city_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

2. In the corresponding Activity, prepare the data source, which can be downloaded from the Internet or read from the database, and use the adapter to transfer the data to the ListView, generally using ArrayAdapter.

//数据源
private String[] data = {"aaa", "bbb", "ccc"};
//参数(当前context, 子项布局id, 数据源),android.R.layout.simple_list_item_1为android内置的布局文件
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
	MainActivity.this, android.R.layout.simple_list_item_1, data);
ListView listView = findViewById(R.id.v_city_list);
//最后调用setAdapter()
listView.setAdapter(adapter);

2. A slightly more complex custom ListView interface

Steps for usage

  1. Define an entity class as the adaptation type of the ListView adapter
  2. Customize a layout file as the layout of the subitem
  3. Custom adapter, inherit ArrayAdapter<generic type is the entity class just defined>
    1. Rewrite a set of constructors of ArrayAdapter, parameters (current context, child layout id, data source)
    2. Override the getVIew() method, which will be called when the subitem is scrolled into the screen.
      1. Get the current item City instance
      2. The convertView parameter is used to cache the previously loaded layout and reuse it later
      3. Load child items when convertView is null
        1. Combining ViewHolder to cache control instances to improve operating efficiency, you can first see the following 3)
        2. Store viewHolder in view, view.setTag(viewHolder)
      4. When it is not null, take out the viewHolder that has been saved to the control instance from convertView, thus avoiding repeated instances of the control and improving efficiency
      5. Control setting operation
      6. back to view
    3. Create a new ViewHolder class to save the instance of the sub-item control to improve efficiency.
  4. Set the data source in the Activity, create an adapter instance with the newly rewritten constructor, and call setAdapter (adapter instance) with the ListView instance. Also add a click listener for the subitem
    1. add some custom class data
    2. Call setAdapter(adapter instance) with ListView instance
    3. Add a click listener for the child
      1. Determine which sub-item the user clicks through the position parameter, and then obtain the corresponding custom class instance

the case

1. Define an entity class as the adaptation type of the ListView adapter

//文件:BasicBean.java

class BasicBean {
    /**
     * cid : CN101281002
     * location : 吴川
     * parent_city : 湛江
     * admin_area : 广东
     */
    private String cid;
    private String location;
    private String parent_city;
    private String admin_area;

    public String getCid() {
        return cid;
    }
    public String getLocation() {
        return location;
    }
    public String getParent_city() {
        return parent_city;
    }
    public String getAdmin_area() {
        return admin_area;
    }
}

2. Customize a layout file as the layout of subitems

//文件:R.layout.city_list_item.xml
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/city_name"
        android:layout_marginTop="20dp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dp"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
    <TextView
        android:id="@+id/parent_city"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
    <TextView
        android:id="@+id/admin_area"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/parent_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</RelativeLayout>

3. Customize the adapter, inherit ArrayAdapter<generic type is the entity class just defined>

//文件:CityAdater.java
//继承ArrayAdapter<泛型为刚定义的实体类>
public class CityAdater extends ArrayAdapter<BasicBean> {
	//布局文件id
    private int resourceId;

	// 1)重写ArrayAdapter的一组构造函数,参数(当前context, 子项布局id, 数据源)
    public CityAdater(Context context, int resource, List<BasicBean> objects) {
        super(context, resource, objects);
        this.resourceId = resource;
    }
	// 2)重写getVIew()方法,子项被滚动进屏幕时会被调用。
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 2-1) 获取当前项City实例
       BasicBean city = getItem(position);
        
        // 2-2) convertView参数用于将之前加载好的布局缓存,之后重用
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
        	// 2-3) 为null时加载子项
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.city_list_item, parent, false);
              // 2-3-1) 结合ViewHolder对控件实例进行缓存,提高运行效率,可先看下面的 3)
            viewHolder = new ViewHolder();
            viewHolder.cityName = view.findViewById(R.id.city_name);
            viewHolder.parentCity = view.findViewById(R.id.parent_city);
            viewHolder.adminArea = view.findViewById(R.id.admin_area);
            // 2-3-2) 将viewHolder存储在view中
            view.setTag(viewHolder);
        } else {
        	// 2-4) 不为null时,从convertView中取出已经保存到控件实例的viewHolder,
        	//这样就避免了控件的重复实例,提高效率
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
		// 2-5) 控件设置操作
        viewHolder.cityName.setText(city.getLocation());
        viewHolder.parentCity.setText(city.getParent_city());
        viewHolder.adminArea.setText(city.getAdmin_area() + ",");
		// 2-6) 返回view
        return view;
    }
	// 3) 新建ViewHolder类保存控件的实例
    class ViewHolder {
        TextView cityName;
        TextView parentCity;
        TextView adminArea;
    }
}

4. Set the data source in the Activity, create an adapter instance with the newly rewritten construction method, and call setAdapter (adapter instance) with the ListView instance. Also add a click listener for the child.

//文件:SearchCity.java
//只写出关键代码 
ListView cityListV = findViewById(R.id.v_city_list);
List<BasicBean> cities = new ArrayList<>();
// 4-1) add一些自定义类的数据
cities.add(new BasicBean(xxx参数xxx));
// 4-2) 用ListView实例调用setAdapter(适配器实例)
CityAdater cityAdater = new CityAdater(SearchCity.this, R.layout.city_list_item, cities);
cityListV.setAdapter(cityAdater);
// 4-3) 添加子项的点击监听器
cityListV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	// 4-3-1) 通过position参数判断出用户点击哪个子项,然后获取相应的自定义类实例
                BasicBean city = cities.get(position);
                String cid = city.getCid();
                //自定义操作
            }
        });

Effect

insert image description here

Attached is the trilogy of Guo Shen's ListView series

  1. https://blog.csdn.net/guolin_blog/article/details/44996879
  2. https://blog.csdn.net/guolin_blog/article/details/45586553
  3. https://blog.csdn.net/guolin_blog/article/details/46361889

Guess you like

Origin blog.csdn.net/weixin_44565784/article/details/100023739