Implement yydatasetchanged and notifyDatasetChanged by yourself

Source: Internet
Author: User

Implement yydatasetchanged and notifyDatasetChanged by yourself

In this blog today, we will implement the most commonly used notifyDatasetChanged feature of the adapter. We will use a LinearLayout to implement a function that may be frequently used in daily work.
You may often encounter the following features in your work:

You need to define a list to display the menu, but this menu is not necessarily suitable for ListView. Then, we may implement it through a LinearLayout.

How can we make LinearLayout more like ListView? Set the Adapter. Your code may be like this.
Extended LinearLayout:

public class MyLinearLayout extends LinearLayout {    private Adapter mAdapter;    public MyLinearLayout(Context context, AttributeSet attrs) {        super(context, attrs);        setOrientation(VERTICAL);    }    public void setAdapter(Adapter adapter) {        removeAllViews();        mAdapter = adapter;        int itemCount = mAdapter.getItemCount();        View child;        for (int i = 0; i < itemCount; i++) {            child = mAdapter.getView(this, i);            addView(child);        }    }}

Implement a simple Adapter by yourself:

public abstract class Adapter {    public abstract int getItemCount();    public abstract View getView(View parent, int position);}

How can we use our code?
First, inherit the Adapter we define

public class MyAdapter extends Adapter {    private ArrayList<String> mData;    public MyAdapter(ArrayList<String> data) {        mData = data;    }    @Override    public int getItemCount() {        return mData.size();    }    @Override    public View getView(View parent, int position) {        TextView textView = new TextView(parent.getContext());        textView.setText(mData.get(position));        return textView;    }}

Set the Adapter for our LinearLayout.

mLinearLayout = (MyLinearLayout) findViewById(R.id.linear);mAdapter = new MyAdapter(mData);mLinearLayout.setAdapter(mAdapter);

These are the most basic code, and may be the case for many friends at work. Therefore, we just want to show the code. As for the effect, it must be a normal vertical LinearLayout. I will not mention it here.
Now, let's assume that the data changes. What should we do with the above Code?
1. Manually call LinearLayout. getChildAt (index) to set data.
2. Reset the adapter. We can see that removeAllViews () is called starting with MyLinearLayout. setAdapter ().

For the first method, we feel that it is contrary to our encapsulation. Every time the data changes, we must manually update the item. However, the second method will definitely affect the performance. After all, every time we add a new view, it seems unnecessary.
So what should we do? To see how the android adapter is implemented, we only need to call yydatasetchanged to OK.
Before we begin to implement yydatasetchanged, we will introduce a concept, that is, the observer mode. java itself provides the implementation of the observer mode, but it is a little troublesome to use, therefore, the android SDK provides us with another method: DataSetObserver. DataSetObserver is actually a simple abstract class, which is also very simple in principle. We can define a DataSetObserver by ourselves. However, we still choose to use the native DataSetObserver. After all, android has provided us.
Here we need to explain that the Code does not have any value, but only has reference significance. Moreover, our code has great limitations, because we only consider TextView.
Let's take a look at our Adapter and add a few lines of code on the above:

public abstract class Adapter {    private DataSetObserver mDataSetObserver;    public void registerObserver(DataSetObserver observer) {        mDataSetObserver = observer;    }    public void unregisterObserver() {        mDataSetObserver = null;    }    public void notifyDataSetChanged() {        if(mDataSetObserver != null) mDataSetObserver.onChanged();    }    public void notifyDataSetInvalidate() {        if(mDataSetObserver != null) mDataSetObserver.onInvalidated();    }    public abstract String getItem(int position);    public abstract int getItemCount();    public abstract View getView(View parent, int position);}

A DataSetObserver variable is added. Correspondingly, two methods are defined to assign values to this DataSetObserver. In addition, a abstract method is added.
public abstract String getItem(int position);
Most importantly, let's take a look at two of the most important methods:

public void notifyDataSetChanged() {        if(mDataSetObserver != null) mDataSetObserver.onChanged();    }    public void notifyDataSetInvalidate() {        if(mDataSetObserver != null) mDataSetObserver.onInvalidated();    }

notifyDataSetChangedMethod, we directly call DataSetObserver. onChanged (), and invalidate is the same. here we need to care where the DataSetObserver is registered.
The modified MyLinearLayout will be published below:

Public class MyLinearLayout extends LinearLayout {private Adapter mAdapter; public MyLinearLayout (Context context, AttributeSet attrs) {super (context, attrs); setOrientation (VERTICAL );} private DataSetObserver mObserver = new DataSetObserver () {public void onChanged () {onChange ();} public void onInvalidated () {removeAllViews () ;}; private void onChange () {int childCount = getChildCount (); int itemCount = mAdapter. getItemCount (); // if there is less data, remove the redundant view if (childCount> itemCount) removeViews (itemCount, childCount-itemCount ); // currently, the number of views <= the number of data TextView child; for (int I = 0; I <itemCount; I ++) {if (I <childCount) {child = (TextView) getChildAt (I); child. setText (mAdapter. getItem (I);} else {child = (TextView) mAdapter. getView (this, I); addView (child) ;}} public void setAdapter (Adapter adapter) {removeAllViews (); mAdapter = adapter; mAdapter. registerObserver (mObserver); int itemCount = mAdapter. getItemCount (); View child; for (int I = 0; I <itemCount; I ++) {child = mAdapter. getView (this, I); addView (child );}}}

In MyLinearLayout, A DataSetObserver is defined and the DataSetObserver is registered with the Adapter in setAdapter. The main code is in the onChanged method of DataSetObserver:

Private void onChange () {int childCount = getChildCount (); int itemCount = mAdapter. getItemCount (); // if there is less data, remove the redundant view if (childCount> itemCount) removeViews (itemCount, childCount-itemCount ); // currently, the number of views <= the number of data TextView child; for (int I = 0; I <itemCount; I ++) {if (I <childCount) {child = (TextView) getChildAt (I); child. setText (mAdapter. getItem (I);} else {child = (TextView) mAdapter. getView (this, I); addView (child );}}}

5th lines of code. If we find that the new dataset is less than before, we will remove the redundant view,
In the next nine rows, We will traverse all the datasets and then upload an if... Else... Yes. If a view exists, only the data is changed. If the data volume is greater than the number of child views, a new view is added.
In this way, the addition and removal operations of view are minimized.
Of course, this code is also very limited, and only TextView can be added, because we have made a strong turn here. This Code only demonstrates how to implement a data observer. OK. Let's take a look at our test code and the final effect:

public class MainActivity extends Activity {    private ArrayList<String> mData = new ArrayList<String>() {        {            for (int i = 0; i < 10; i++) {                add("android " + i);            }        }    };    private MyLinearLayout mLinearLayout;    private MyAdapter mAdapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mLinearLayout = (MyLinearLayout) findViewById(R.id.linear);        mAdapter = new MyAdapter(mData);        mLinearLayout.setAdapter(mAdapter);        mLinearLayout.postDelayed(new Runnable() {            @Override            public void run() {                for (int i = 0; i < 10; i++) {                    mData.add("loader " + i);                }                mAdapter.notifyDataSetChanged();            }        }, 2000);        mLinearLayout.postDelayed(new Runnable() {            @Override            public void run() {                for (int i = 0; i < 5; i++) {                    mData.remove(0);                }                mAdapter.notifyDataSetChanged();            }        }, 4000);        mLinearLayout.postDelayed(new Runnable() {            @Override            public void run() {                mAdapter.notifyDataSetInvalidate();            }        }, 6000);    }}

The effect is as follows:

Finally, download the code: Download the code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.