Reputation: 5
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;
}
});
Upvotes: 0
Views: 317
Reputation: 1526
An additional reference about why XML is "kinda" convention when it comes to android UI resources:
http://developer.android.com/guide/topics/ui/declaring-layout.html
The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML. If you're interested in instantiating View objects at runtime, refer to the ViewGroup and View class references.
While you're free to choose, please stick to XML whenever you can.
Upvotes: 0
Reputation: 1669
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:
Upvotes: 2