Reputation: 86600
I'm quite new to Android Studio and I want to have quick access to views such as buttons, image views, text views, etc.
So far I know the method findViewById
, and this is what I'm doing to create easy access to views:
Button btn1, btn2, btn3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btn1=(Button)findViewById(R.id.btn1);
this.btn2=(Button)findViewById(R.id.btn2);
this.btn3=(Button)findViewById(R.id.btn3);
}
//then I simply use my defined vars
Although it works, it's still quite boring to have to write all this code (or to have to use findViewById
every time, with a cumbersome way of getting ids and still adding a cast).
Is this really the best way of doing this?
Upvotes: 1
Views: 2234
Reputation: 1788
Since nobody has mentioned this in any of their answers, Kotlin is now officially supported for android development and there is the android kotlin extension (https://kotlinlang.org/docs/tutorials/android-plugin.html) which allows you to access the views directly without findViewById().
If you do decide to use it, just be aware that if you use it in a fragment, you have to use it after passing the view in onCreateView() or else it will not find the views.
If you are not ready for Kotlin, then I would highly recommend data binding over butterknife or any other solution because this is the direction Google is going with android.
Upvotes: 1
Reputation:
In android O you don't need to write (Cast) before the findViewById
, Also there is third part library called ButterKnife with applying the plugin and generating it you can handle this issue very easy.
Upvotes: 3
Reputation: 12222
you can use 3 way :
1.findViewById
normal way but The hardest. you can use plugin findviewbyme (link) for speed up write code
2.butterknife Library
when use this lib, the code gets less.you can check this link
3.Data Binding Library
Is the best way, just after initial binding, when add new view in layout, you have access to it without any additional code. you can check this (link)
Upvotes: 3
Reputation: 3702
There are libraries such as AndroidAnnotation and ButterKnife you may be interested in. This is how your code would look like if you use Android Annotation.
@EActivity(R.layout.activity_main)
public class MainActivity extends Actiivty {
@ViewById
Button btn1, btn2, btn3;
}
Upvotes: 2
Reputation: 5496
You can check out library like Butterknife http://jakewharton.github.io/butterknife/.
It prevents you from writing boilerplate code - simply inject views. You can combine it with this Android Studio plugin: https://plugins.jetbrains.com/plugin/7369-android-butterknife-zelezny
With this set up injecting views is really simple and fast.
Also, you can check out topic like "databinding" https://developer.android.com/topic/libraries/data-binding/index.html It is also a good approach to have views defined for you.
Upvotes: 4