Issue
I've tried using the include/merge tools in the android studio docs, but all I can mess with is the "look" (layout parameters) of the buttons. (i.e. the location, font size, color)
What I'd like to do is load hundreds of layouts in a certain order, controlled via buttons.
For example: Button_1 on Screen_1 takes you to Screen_2. Screen_2 has Button_1 too, but re-packaged with a new way for it to load up the Screen_3 layout.
Does Android Studio allow you to reuse the same button with different functionality, or are we stuck with overwriting the visuals only?
There's a small voice in the back of my head telling me that doing it this way will make my app too big. If there's a better way to get this same effect without needing to re-draw a new layout each time.
Solution
Does Android Studio allow you to reuse the same button with different functionality, or are we stuck with overwriting the visuals only?
To reuse the same Button in different Screens but also reuse some button functionalities can be achieved by using a custom Button View.
Let's say you want to reuse a specific MaterialButton.
1.Create a custom button eg: MyReuseButton
which is a subclass of MaterialButton
like below:
public class MyReuseButton extends MaterialButton {
public MyReuseButton(@NonNull Context context) {
super(context);
init();
}
public MyReuseButton(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public MyReuseButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
//these are the default Button attributes
setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.darker_gray));
setTextColor(ContextCompat.getColor(getContext(), android.R.color.black));
setText("My Button Default Text");
}
public void setButtonLogicForScreen1(){
//do your button functionalities for Screen1 (which is also reused in case some other screen needs the same functionalities)
}
public void setButtonLogicForScreen2(){
//do your button functionalities for Screen2 (which is also reused in case some other screen needs the same functionalities)
}
}
2.You can reuse this button in every screen you want using a different ID like below:
<com.my.packagename.MyReuseButton
android:id="@+id/myButtonId1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
3.And of course you can reuse some Button functionalities eg: for Screen 1 like:
MyReuseButton myReuseButton = findViewById(R.id.myButtonId1);
myReuseButton.setButtonLogicForScreen1(); //of course this can be reused over other screens as well
or in Screen 2:
MyReuseButton myReuseButton = findViewById(R.id.myButtonId2);
myReuseButton.setButtonLogicForScreen2(); //of course this can be reused over other screens as well
Answered By - MariosP
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.