6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ListViewにObservableArrayListを使う(Android)

6
Posted at

kgmyshinさんの
Data Bindingつかってみた
を参考にして、Data Bindingを試してみた。

各アイテムについてはnotifyPropertyChangedを呼び出すことで、動的に書き換えができる。
ObservableArrayListを使うと追加イベントを監視できるので、アイテムの追加も動的に反映できる。

ObservableListAdapter

アダプタは、OnListChangedCallbackで更新を教えてもらう
https://github.com/firewood/observable_listview/blob/master/app/src/main/java/info/competitiveprogramming/observablelistview/ObservableListAdapter.java

public class ObservableListAdapter extends ArrayAdapter<SimpleMessage> {
    public ObservableListAdapter(Context context, ObservableArrayList<SimpleMessage> data) {
        super(context, R.layout.list_simple_message, data);
        data.addOnListChangedCallback(new ObservableArrayList.OnListChangedCallback<ObservableArrayList<SimpleMessage>>() {
            @Override
            public void onChanged(ObservableArrayList<SimpleMessage> simpleMessages) {
                notifyDataSetChanged();
            }

MainActivity

リストを作成してListViewのアダプタに設定
https://github.com/firewood/observable_listview/blob/master/app/src/main/java/info/competitiveprogramming/observablelistview/MainActivity.java

        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        data = new ObservableArrayList<>();
        adapter = new ObservableListAdapter(this, data);
        binding.list.setAdapter(adapter);

追加するとその場で反映される

        SimpleMessage a;
        a = new SimpleMessage();
        a.title = "hoge";
        data.add(a);

サンプル

Addをタップするとアイテムを追加、Changeをタップするとアイテムの中身が変わります。
https://github.com/firewood/observable_listview

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?