DataBinding 與 ListView 、RecyclerView 實現數據雙向綁定

ListView

佈局較簡單兩個Button 一個ListView

<?xml version="1.0" encoding="utf-8"?>
<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"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加數據"
            />
        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改數據"
            />
    </LinearLayout>

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

</LinearLayout>

Student對象

public class Student {
    public ObservableField<String> name = new ObservableField<>();
    public ObservableInt age = new ObservableInt();
    public ObservableBoolean isBoy = new ObservableBoolean();
    public Student(String name,int age,boolean isBoy){
        this.name.set(name);
        this.age.set(age);
        this.isBoy.set(isBoy);
    }
}

item_student_layout.xml 內容

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="student"
            type="com.example.databinding.Student"/>
    </data>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        >
        <TextView android:layout_width="0dp"
                  android:layout_height="wrap_content"
                  android:layout_weight="1"
                  android:textColor="@color/colorBlack"
                  android:text="@{student.name}"/>
        <TextView android:layout_width="0dp"
                  android:layout_weight="1"
                  android:layout_height="wrap_content"
                  android:textColor="@color/colorBlack"
                  android:text='@{"" +student.age}'/>
        <TextView android:layout_width="0dp"
                  android:layout_weight="1"
                  android:layout_height="wrap_content"
                  android:textColor="@color/colorBlack"
                  android:text='@{student.isBoy?"男":"女"}'/>
    </LinearLayout>
</layout>

StudentAdapter

public class StudentAdapter extends BaseAdapter {
    private List<Student> studentList;
    private Context context;
    public StudentAdapter(Context context, List<Student> studentList) {
        this.studentList = studentList ;
        this.context = context ;
    }

    @Override
    public int getCount() {
        return studentList.size();
    }

    @Override
    public Student getItem(int position) {
        return studentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemStudentLayoutBinding itemStudentLayoutBinding = null;
        if (convertView == null){
            itemStudentLayoutBinding = DataBindingUtil.inflate(LayoutInflater.from(context),R.layout.item_student_layout,parent,false);
            convertView = itemStudentLayoutBinding.getRoot();
        }else {
            itemStudentLayoutBinding = DataBindingUtil.getBinding(convertView);
        }
        itemStudentLayoutBinding.setStudent(studentList.get(position));

        return itemStudentLayoutBinding.getRoot();
    }
}

Adapter中加載佈局,官方文檔給的很明確
adapter.png

Avtivity中代碼

public class ListViewActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView mListView;
    private List<Student> mStudentList;
    private StudentAdapter mStudentAdapter;
    private Button mAddButton;
    private Button mUpdateButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);

        mListView = (ListView) findViewById(R.id.list_view);
        mAddButton = (Button) findViewById(R.id.btn_add);
        mUpdateButton = (Button) findViewById(R.id.btn_update);

        mAddButton.setOnClickListener(this);
        mUpdateButton.setOnClickListener(this);

        initData();

    }

    private void initData() {
        mStudentList = new ArrayList<>();
        for (int i = 0 ; i < 5 ; i++){
            Student student = new Student("小老虎",18,true);
            mStudentList.add(student);
        }
        mStudentAdapter = new StudentAdapter(getApplicationContext(), mStudentList);
        mListView.setAdapter(mStudentAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add:
                Student student = new Student("青蛙",28,false);
                mStudentList.add(student);
                mStudentAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_update:
                mStudentList.get(0).name.set("河馬呱呱叫");
                break;
            default:
                break;
        }
    }
}

初始化數據沒什麼好說的。
添加按鈕中添加Student對象並刷新ListView
修改按鈕中 修改Student集合中的第一個Student對象的名字爲 河馬呱呱叫 。
效果如下。
list.gif

RecyclerView

界面不變,只是將ListView佈局改爲RecyclerView 。當然得依賴design包

<?xml version="1.0" encoding="utf-8"?>
<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"
   >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加數據"
            />
        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改數據"
            />
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

RecyclerAdapter

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private List<Student> studentList;
    private Context context;
    public RecyclerAdapter(Context context,List<Student> studentList) {
        this.studentList = studentList ;
        this.context = context ;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ItemStudentLayoutBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_student_layout, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.binding.setStudent(studentList.get(position));
        holder.binding.executePendingBindings();
    }


    @Override
    public int getItemCount() {
        return studentList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public ItemStudentLayoutBinding binding;

        public ViewHolder(ItemStudentLayoutBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}

Activity

public class RecyclerViewActivity extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView mRecyclerView;
    private Button mAddButton;
    private Button mUpdateButton;
    private RecyclerAdapter mRecyclerAdapter;
    private List<Student> mStudentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycle_view);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mAddButton = (Button) findViewById(R.id.btn_add);
        mUpdateButton = (Button) findViewById(R.id.btn_update);
        mAddButton.setOnClickListener(this);
        mUpdateButton.setOnClickListener(this);
        initData();
    }

    private void initData() {
        mStudentList = new ArrayList<>();
        for (int i = 0 ; i < 5 ; i++){
            Student student = new Student("小老虎",18,true);
            mStudentList.add(student);
        }
        mRecyclerAdapter = new RecyclerAdapter(getApplicationContext(), mStudentList);

        mRecyclerView.setAdapter(mRecyclerAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add:
                Student student = new Student("青蛙",28,false);
                mStudentList.add(student);
                mRecyclerAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_update:
                mStudentList.get(0).name.set("河馬呱呱叫");
                break;
            default:
                break;
        }
    }
}

運行之後和ListView效果一樣。只是Adapter中寫法不同。
recycler.gif

歡迎關注Android小菜菜公衆號
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章