땀이 삐질삐질 나는 개발 일기

Recyclerview Databinding 코드 예제 본문

개발 Tip

Recyclerview Databinding 코드 예제

삐질 2019. 6. 4. 21:55
안녕하세요. 삐질삐질 개발하는 개발자 삐질입니다.

오늘은 MVVM과 Databinding을 이용해  Recyclerview를 사용 하는 방법에 대해 알아보고자 합니다.



데이터 바인딩을 하기 위해서는 gradle에 추가해야 할 옵션이 있습니다.
https://ppizil.tistory.com/26 이 글부터 읽고 봐주세요 ~~~~ 
  1. MainActivity.java 
public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private MemoViewModel viewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        init();
    }

    public void init() {
        viewModel = new MemoViewModel();
        viewModel.onCreate();

        binding.setViewmodel(viewModel);
        binding.setLifecycleOwner(this);
    }


}

  1. MemoViewModel.java

public class MemoViewModel {

    private List<Memo> items;
    private RecyclerAdapter adapter;


    public MemoViewModel() {
        if (items == null) {
            items = new ArrayList<>();
        }

        if (adapter == null) {
            adapter = new RecyclerAdapter(this);
        }
        testLogic();
    }

    public void testLogic() {
        for (int i = 0; i < 30; i++) {
            Memo memo = new Memo();
            memo.setId(i);
            memo.setMemoContext("테스트 메몸입니다. " + i);
            memo.setTitle(i + "번째 메모 제목입니다.");
            items.add(memo);
        }
    }

    public void onCreate() {
        adapter.notifyDataSetChanged();
    }

    public void onResume() {

    }

    public RecyclerAdapter getAdapter() {
        return adapter;
    }

    public List<Memo> getItems() {
        return items;
    }

    public String getTitle(int pos) {
        return items.get(pos).getTitle();
    }

    public String getContents(int pos) {
        return items.get(pos).getMemoContext();
    }
}


  1. RecyclerAdapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private MemoViewModel viewModel;

    public RecyclerAdapter(MemoViewModel viewModel) {
        this.viewModel = viewModel;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemMemoBinding binding = ItemMemoBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ItemViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            ((ItemViewHolder) holder).bind(viewModel, position);
        }
    }


    @Override
    public int getItemCount() {
        return viewModel.getItems() == null ? 0 : viewModel.getItems().size();
    }


    public static class ItemViewHolder extends RecyclerView.ViewHolder {
        private ItemMemoBinding binding;

        public ItemViewHolder(ItemMemoBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        public void bind(MemoViewModel viewModel, int pos) {
            binding.setViewmodel(viewModel);
            binding.setPos(pos);
            binding.executePendingBindings();
        }
    }
}


  1. Memo.java

public class Memo {

    int id;
    String title;
    String memoContext;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMemoContext() {
        return memoContext;
    }

    public void setMemoContext(String memoContext) {
        this.memoContext = memoContext;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

  1. CustomAdapter.java
public class CustomAdapter {

    @BindingAdapter("bind:verAdapter")
    public static void verAdapter(RecyclerView recyclerView, RecyclerView.Adapter<?> adapter) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(recyclerView.getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
    }


}

  1. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

    <data>

        <variable
            name="viewmodel"
            type="com.ppizil.recyclerviewtest.MemoViewModel" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            bind:verAdapter="@{viewmodel.getAdapter()}"></androidx.recyclerview.widget.RecyclerView>
    </LinearLayout>
</layout>

  1. item_memo.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="viewmodel"
            type="com.ppizil.recyclerviewtest.MemoViewModel" />

        <variable
            name="pos"
            type="Integer" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="15dp">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{viewmodel.getTitle(pos)}"
            android:textSize="14dp" />

        <TextView
            android:id="@+id/contents"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:text="@{viewmodel.getContents(pos)}"
            android:textColor="#000000"
            android:textSize="18dp" />
    </LinearLayout>
</layout>


안드로이드 초보 개발자를 위해 아래와 같은 카카오 오픈톡을 운영 중입니다. 




Comments