【问题标题】:Android: xml selector for buttonAndroid:按钮的xml选择器
【发布时间】:2017-04-11 15:16:39
【问题描述】:

我正在尝试使用 xml 选择器来更改按下图像按钮时的图像,但我遇到了一些问题。首先,图像以不同的尺寸出现在屏幕上,其次,按钮仅在单击时更改颜色,但在其处于活动状态时不会更改。

这是带有图像按钮的 布局 的 xml:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/coupon_filter_btns"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="#a7a7a7"
    android:weightSum="7"
    >


    <ImageButton
        android:id="@+id/filter_greece"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:scaleType="fitCenter"
        android:src="@drawable/greece"
        android:layout_weight="1"
        android:background="@drawable/greece"
        android:paddingTop="4dp"
        android:paddingBottom="4dp"
        />
     <ImageButton/>
     <ImageButton/>
</LinearLayout>

下面是名为greece.xml的选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/greece_active" android:state_selected="true"></item>

<item android:drawable="@drawable/greece_active" android:state_focused="true"></item>

<item android:drawable="@drawable/greece_active" android:state_pressed="true"></item>

<item android:drawable="@drawable/filter_white_greece"></item>

</selector>

这是使用按钮的java代码:

 ImageView filterGreece = (ImageView) kati.findViewById(R.id.filter_greece);
    filterGreece.setBackgroundResource(R.drawable.greece);
    filterGreece.setOnClickListener(new ViewListeners(this.getContext()).new OneFragmentFilters(OneFragment.this)  ) ;

【问题讨论】:

  • “按钮仅在单击时更改颜色,但在其处于活动状态时不会更改”您能进一步解释一下吗?
  • 我希望按钮在标签处于活动状态时具有另一种颜色,而不仅仅是在单击时

标签: java android xml selector imagebutton


【解决方案1】:

好的,首先你的 XML 中有错误

你只是将drawable设置为背景而不是Src

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/coupon_filter_btns"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="#a7a7a7"
    android:weightSum="7"
    >


    <ImageButton
        android:id="@+id/filter_greece"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:scaleType="fitCenter"
         android:layout_weight="1"
        android:background="@drawable/greece"
        android:paddingTop="4dp"
        android:paddingBottom="4dp"
        />
  </LinearLayout>

第二个选择器在没有

的情况下也能正常工作
filterGreece.setBackgroundResource(R.drawable.greece);

所以删除这条线

【讨论】:

  • 感谢您的回复,真的很有帮助。正如我上面提到的,我希望按钮在它们所代表的屏幕显示时保持活动状态。知道我该怎么做吗?
猜你喜欢
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
相关资源
最近更新 更多