Showing posts with label view binding. Show all posts

Android ButterKnife View Binding

Android ButterKnife View Binding

In this android tutorial, I am going to show how to use Android ButterKnife View Binding in android application development. If you have been developing android application, you will realized that there are lots of boilerplate codes in your application. In some cases, it will be too much that the onCreate() method will be bloated with boilerplate codes. This is where Android ButterKnife comes to your help.

How it can help us to improve your code

  1. Eliminate findViewById calls by using @BindView on fields. 
  2. Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties. 
  3. Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others. Eliminate resource lookups by using resource annotations on fields. 
In this post, I am going to show the method of using ButterKnife in RecyclerView and Each Single Views.

Creating New Project with Android Studio

  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.
    Android
    Figure 1
  3. Click finish button to create a new project in Android Studio.

Project Setup: 

Open App Level build.gradle file and add the following lines as mentioned.
...
// add the below lines in dependencies
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
...

Coding Part

Method to use ButterKnife: In your Activity, add the following line
// Initialize ButterKnife 
ButterKnife.bind(this);
Each View is initialized as in the following
@BindView(R.id.title)
public TextView title;
RecyclerView is initialized as in the following
@BindView(R.id.recycler)
public RecyclerView recyclerView;
Create ToDoViewHolder.java and Paste the following code
class ToDoViewHolder extends RecyclerView.ViewHolder{

    @BindView(R.id.todo_type)
    TextView todoType;
    @BindView(R.id.todo)
    TextView todo;

    ToDoViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

}
Create ToDoObject.java and add the following lines
class ToDoObject {
    private String todoType;
    private String todoName;

    ToDoObject(String todoType, String todoName) {
        this.todoType = todoType;
        this.todoName = todoName;
    }

    String getTodoType() {
        return todoType;
    }

    String getTodoName() {
        return todoName;
    }

}
Create ToDoAdapter.java and add the following lines
class ToDoAdapter extends RecyclerView.Adapter {
    private Context context;
    private List toDoObjectList;

    ToDoAdapter(Context context, List toDoObjectList) {
        this.context = context;
        this.toDoObjectList = toDoObjectList;
    }

    @Override
    public ToDoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false);
        return new ToDoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ToDoViewHolder holder, final int position) {
        ToDoObject toDoObject = toDoObjectList.get(position);
        holder.todoType.setText(toDoObject.getTodoType());
        holder.todo.setText(toDoObject.getTodoName());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "Selected index " + position, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return toDoObjectList.size();
    }
}
Finally Create ToDoActivity.java and call your Adapter as usual for RecyclerView. The Complete Code for ToDoActivity.java is given below
public class ToDoActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    public Toolbar toolbar;

    @BindView(R.id.fab)
    public FloatingActionButton fab;

    @BindView(R.id.recycler)
    public RecyclerView recyclerView;

    @BindView(R.id.title)
    public TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        title.setText("ToDo List");
        title.setTextSize(20);

        LinearLayoutManager layoutManager = new LinearLayoutManager(ToDoActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        ToDoAdapter mAdapter = new ToDoAdapter(ToDoActivity.this, getTestData());
        recyclerView.setAdapter(mAdapter);

    }

    public List getTestData() {
        List cars = new ArrayList<>();
        cars.add(new ToDoObject("Shopping", "Cake"));
        cars.add(new ToDoObject("Shopping", "Cloth"));
        cars.add(new ToDoObject("Shopping", "Color Paper"));
        cars.add(new ToDoObject("HomeWork", "Science"));
        cars.add(new ToDoObject("HomeWork", "Maths"));
        cars.add(new ToDoObject("HomeWork", "Chemistry"));
        return cars;
    }

}
For Full Reference, Download whole source code from the github link and post your comments. If you like this post, provide one star in Github or Like my Page. For any suggestions, feel free to post comments.

For more, Details Please download whole project source from Github.

Download From Github