ListView data update problem


Introduction to this section:

We have already learned some basic usage of ListView, but if you are careful, you may find that our data What is defined at the beginning is all static, but in actual development, our data often changes dynamically, such as If I add or delete a certain column, the data displayed in the list should also be updated synchronously, so we will discuss this in this section. Next, let’s start this section on the issue of updating ListView data, including all updates and one of them. ~


1. Write a normal demo first

Okay, let’s write a normal demo first. Let’s adjust it slowly later:

entity class: Data.java

/**
 * Created by Jay on 2015/9/21 0021.
 */
public class Data {
private int imgId;
private String content;

public Data() {}

public Data(int imgId, String content) {
this.imgId = imgId;
this.content = content;
}

public int getImgId() {
return imgId;
}

public String getContent() {
return content;
}

public void setImgId(int imgId) {
this.imgId = imgId;
}

public void setContent(String content) {
this. content = content;
}
}

Activity布局以及列表项布局

activity_main.xml

<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"
    tools:context=".MainActivity">

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

</LinearLayout>

item_list.xml:

<?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"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="56dp"
        android:layout_height="56dp"/>

    <TextView
        android:id="@+id/txt_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"
        android:textSize="18sp" />

</LinearLayout>

自定义BaseAdapter的实现:MyAdapter.java

MainActivity.java的编写:

public class MainActivity extends AppCompatActivity {

    private ListView list_one;
    private MyAdapter mAdapter = null;
    private List<Data> mData = null;
    private Context mContext = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        bindViews();
        mData = new LinkedList<Data>();
        mAdapter = new MyAdapter((LinkedList<Data>) mData,mContext);
        list_one.setAdapter(mAdapter);
    }

    private void bindViews(){
        list_one = (ListView) findViewById(R.id.list_one);
    }

}

It can be run. After running it, we found that our page does not have any data and is completely white. This kind of user experience is not good. We can call a setEmptyView(View) method of ListView. When the ListView data is empty, Display a corresponding View. In addition, I found that this method is very strange. The dynamically added View is invalid and can only be displayed in ListView. Add the View you want to display when the ListView has no data in the layout file, and use this setEmptyView to set it View, it won't be displayed when loading. It's so strange... For example, when there is no data, it will display a "No data" TextView, part of the code is as follows:

<TextView
android:id="@+id/txt_empty"
android:layout_width="wrap_content"
android:layout_height= "wrap_content"
android:layout_gravity="center"
android:textSize="15pt"
android:textColor="#000000"/>

txt_empty = (TextView) findViewById( R.id.txt_empty);
txt_empty.setText("No data~");
list_one.setEmptyView(txt_empty);

Of course, in addition to this method, we can also Define a layout with the same size and position as the ListView, and then set it, android:visibility="gone", determine the size of the mData collection in Java code, if ==0, It means there is no data, let this layout be displayed, and when there is data, let this layout be hidden~


2. Add a record

Okay, let's get an add button, no Click to add one record at a time~

Running renderings:

2.gif

Code implementation

In our customization Define a method in BaseAdapter, the method content is as follows:

public void add(Data data) {
if (mData == null) {
mData = new LinkedList<>( );
}
mData.add(data);
notifyDataSetChanged();
}

Then add a button to the layout, and then set the event. The code is as follows:

private Button btn_add;
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_add:
          mAdapter.add(new Data(R.mipmap.ic_icon_qitao, "Kneel down to Brother Pig~~~ x " + flag));
                                                                                                             

##Hey, it’s done. It’s that simple to add data~. If you want to insert it into a specific position, that’s fine. In our Adapter class, add another Write a method:
//往特定位置,添加一个元素
public void add(int position,Data data){
    if (mData == null) {
        mData = new LinkedList<>();
    }
    mData.add(position,data);
    notifyDataSetChanged();
}
然后加个按钮,写个事件:
private Button btn_add2;

btn_add2 = (Button) findViewById(R.id.btn_add2);

btn_add2.setOnClickListener(this);
case R.id.btn_add2:
//position starts from 0
mAdapter.add(4,new Data(R.mipmap.ic_icon_qitao,"Kneel down for Brother Pig~~~ x " + flag ));
break;



Running rendering:

You can see that our ninth item is inserted into the fifth position ~

3.gif3. Delete a certain item

Similarly, we write two methods, one to delete the object directly, and the other to delete based on the cursor:

public void remove(Data data) {

if(mData != null) {

mData.remove(data);
}
notifyDataSetChanged();
}

public void remove(int position) {
if(mData != null) {
mData.remove(position);
}
notifyDataSetChanged();
}


Then add two Buttons and call these two methods:
case R.id.btn_remove:

mAdapter.remove(mData_5);

break;
case R.id.btn_remove2:
mAdapter.remove(2);
break;

Running renderings:

4.gif

We can see from the picture that the fifth item has been removed, and then click the cursor to delete the data, It’s the third item that I keep deleting!


4. Remove all records:

This is simpler, just call the clear method directly! The method code is as follows:

public void clear() {
if(mData != null) {
mData.clear();
notifyDataSetChanged ();
}

5. Update a certain record

If you are careful, you should find that after data modification operation, a notifyDataSetChanged(() is called );

At first I thought:

##notifyDataSetChanged() will redraw all the actual items on the interface, which will affect the UI performance. If the amount of data It's big, but if I change one item, I have to redraw all the items. This is definitely unreasonable, right? So, I used a stupid method To modify the value of the control in an Item, I wrote this code in the Java code:

private void updateListItem(int postion,Data mData){
int visiblePosition = list_one.getFirstVisiblePosition();
View v = list_one.getChildAt(postion - visiblePosition);
ImageView img = (ImageView) v.findViewById(R.id.img_icon);
TextView tv = (TextView) v.findViewById(R.id.txt_content);
img.setImageResource(mData.getImgId());
tv.setText(mData.getContent());
}

Later I discussed with friends in the group and found that I was wrong

:

The notifyDataSetChanged() method will determine whether re-rendering is needed. If the current item does not need to be re-rendered, It will not be re-rendered. If the status of an Item changes, it will cause the View to be redrawn, and what is redrawn is not All Items, but the Item whose View state changes! So we directly notifyDataSetChange() method That’s it, of course it doesn’t matter if you know one more of the above methods~

Code download:

ListViewDemo3.zip

Summary of this section:

Okay, this section tells you about the implementation of data update in ListView, of course not only ListView, but also other Adapters Class controls can call these methods to complete data updates~That’s all~Thank you