android 使用按钮选择器 xml 和 imageview 的 setimage 哪个更好?

android which is better to use button selector xml or imageview's setimage?

我正在开发一个带有一些按钮的应用程序,这些按钮在图像内部,按下它后,图像会与另一个图像发生变化。现在,最好使用 xml 选择器,并设置按钮的背景 = "selector"... 像这样(即使有很多按钮也会有很多可绘制对象和很多选择器) :

<?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>

或者像这样在 ACTION.DOWN 上设置图像的侦听器:

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;
            }
        });

我个人认为,如果可以(除非您需要根据某些输入动态地进行布局),最好始终使用 XML,而不是以编程方式进行布局,因为它保持代码干净并使布局与应用程序逻辑代码分开。

基于 XML 的布局的一般优点:

  • 您可以在 Android Studio/eclipse
  • 中使用布局编辑器
  • 您可以在应用的其他地方重复使用该布局
  • 允许您在布局与应用程序逻辑和功能之间进行分离。

有关 XML 为什么在 android UI 资源方面是 "kinda" 约定的附加参考:

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.

虽然您可以自由选择,但请尽可能坚持XML。