Wednesday, December 16, 2015

Butterknife Library for Android

Butterknife 

Is a view "injection" library for Android. It will reduces boilerplate code.

Example:
  1. Add dependency to app/build.gradle
dependencies {
  compile 'com.jakewharton:butterknife:7.0.1'
}
  1. In main.xml declare an image widget id name "image"
  2. In main.java start using @Bind to declare each variable 

public class Main extends AppCompatActivity {
private static final String ITENT_TAG= "chapter"; 

private Chapter chapter;

@Bind(R.id.button) Button myButton; 

@Bind(R.id.textTextView myText;

@Bind(R.id.image

ImageView myImage;  

@Override public void onCreate(Bundle savedInstanceState) 

{
super.onCreate(savedInstanceState);   setContentView(R.layout.activity_detail);   ButterKnife.bind(this); 

@OnClick(R.id.button) protected void Toast(){

Toast.makeText(getApplicationContext(),"Hello Android Butter Knife",Toast.LENGTH_LONG).show();}

}

myText.setText("Hello!");

res = getResources();
myImage.setImageDrawable(res.getDrawable(R.drawable.myimage));



  • Also initialize ButterKnife in OnCreate:
 ButterKnife.bind(this);


Resources:
http://www.sitepoint.com/tidying-code-with-android-butterknife/
https://guides.codepath.com/android/Reducing-View-Boilerplate-with-Butterknife

No comments:

Post a Comment