This is not data binding, this is View binding which is new to Android Studio 3.6 Canary 11+ described here.
For using inside an Activity it is clear, you just use it like this:
Let's say we have a layout named activity_main.xml
Then in the code we can use it like this:
public class MainActivity extends Activity{ ActivityMainBinding binding; //Name of the layout in camel case + "Binding" @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); } }
However, It's not clear how to use View Binding with RecyclerView?
Edit: Please explain in Java.
Let's say we have a RecyclerView inside activity_main.xml
and its id is "@+id/rv_test"
Inside the Activity we can use it like so:
public class MainActivity extends Activity{ ActivityMainBinding binding; //Name of the layout in camel case + "Binding" @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); binding.rvTest.setLayoutManager(layoutManager); } }
Let's name the layout for RecyclerView items test_list_item.xml
Then we can implement our adapter inside Activity like this:
public class MainActivity extends Activity{ ActivityMainBinding binding; //Name of the layout in camel case + "Binding" @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); binding.rvTest.setLayoutManager(layoutManager); List<String> items = Arrays.asList("item", "item", "item"); binding.rvTest.setAdapter(new MyAdapter(items)); } private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{ private List<String> items; private class MyViewHolder extends RecyclerView.ViewHolder{ TestListItemBinding binding;//Name of the test_list_item.xml in camel case + "Binding" public MyViewHolder(TestListItemBinding b){ super(b.getRoot()); binding = b; } } public MyAdapter(List<String> items){ this.items = items; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){ return new MyViewHolder(TestListItemBinding.inflate(getLayoutInflater())); } @Override public void onBindViewHolder(MyViewHolder holder, int position){ String text = String.format(Locale.ENGLISH, "%s %d", items.get(position), position); //An example of how to use the bindings holder.binding.tvTest.setText(text); } @Override public int getItemCount(){ return items.size(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With