【问题标题】:Android button states programmatically in Java (not XML)Android 按钮状态在 Java 中以编程方式(不是 XML)
【发布时间】:2011-12-07 06:46:14
【问题描述】:

如何为“state_pressed”定义 Android 按钮图像 Java中的“android:state_focused”?

例如,如何在 Java 中实现 XML 的等价物

http://developer.android.com/reference/android/widget/ImageButton.html

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
     <item android:drawable="@drawable/button_normal" /> <!-- default -->
 </selector>

【问题讨论】:

标签: android user-interface


【解决方案1】:

只需使用StateListDrawable的addState方法

StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, 
      getResources().getDrawable(R.drawable.phone));

这个方法的第一个参数可以使用下面的常量

android.R.attr.state_accelerated
android.R.attr.state_activated
android.R.attr.state_active
android.R.attr.state_drag_can_accept
android.R.attr.state_drag_hovered
android.R.attr.state_enabled
android.R.attr.state_first
android.R.attr.state_focused
android.R.attr.state_hovered
android.R.attr.state_last
android.R.attr.state_middle
android.R.attr.state_pressed
android.R.attr.state_selected
android.R.attr.state_single
android.R.attr.state_window_focused

【讨论】:

  • 我发现以下示例非常有用,因为它还展示了如何使用“假”状态(带有前导减号)heliodorj.blogspot.com/2009/04/…
  • 默认状态是什么?
  • 默认状态如下:stateListDrawable.addState(new int[] {}, new ColorDrawable(getResources().getColor(R.color.red)));
  • @SomeoneSomewhere 非常感谢你,我一直在寻找以编程方式设置 state_activated="false" 几个小时!
【解决方案2】:

创建StateListDrawable 的实例,然后将其分配给imagebutton.setImageDrawable(stateDrawable)

【讨论】:

    【解决方案3】:

    10x to Tang Ke,我将它用于不同的列表项颜色和选择颜色。

    选中状态

    stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, 
      new ColorDrawable(getResources().getColor(R.color.alpha_blue500)));
    

    默认状态

    stateListDrawable.addState(new int[] {}, 
      new ColorDrawable(getResources().getColor(R.color.red)));
    

    您可以在此处更改行项目的不同状态的颜色(例如付费与免费)

    将状态设置为列表适配器中的自定义布局行项

    holder.relativeLayout.setBackgroundDrawable(stateListDrawable);
    

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多