Issue
i'm developing an app with some buttons with inside an image that after pressed it, changes image with another one. Now, is better to use an xml selector, and set the button's background = "selector"... like this (even if with many buttons there will be a lot of drawables and a lot of selector too):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@drawable/start"/>
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/start_press"/>
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/start"/>
<item
android:state_enabled="true"
android:drawable="@drawable/start"/>
</selector>
or a listener with a setimage on ACTION.DOWN like this:
ser6.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
ser6.setImageResource(R.drawable.ser_press);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
goNext();
}
return true;
}
});
Solution
I personally think it is better to always use the XML if you can (unless you need to do it dynamically based on some input) when it comes to layout rather than doing it programmatically as it keeps the code clean and keeps the layout separate from the application logic code.
Advantages of XML based layouts in general:
- You can use layout editors in Android Studio/eclipse
- You can reuse the layout in other places of the app
- Allows you have separation between layout and application logic and functionality.
Answered By - pgiitu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.