Langsung ke konten utama

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.

Project Setup: 

Open Project Level build.gradle file and add the following line.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
Open App Level build.gradle file and add the following lines as mentioned.
// Add plugin below 
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
...
// add the below lines in dependencies
compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'
...
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;

Source Code

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

Komentar

Postingan populer dari blog ini

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the xcode proje

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail