单击事件更改按钮背景颜色?

时间:2015-04-12 13:46:09

标签: java android android-layout android-fragments android-button

当我在活动上声明一个按钮并设置android:onClick属性时,活动会在按下时自动更改按钮的背景颜色。

现在我的片段上有一个按钮。由于我无法在此处使用android:onClick,因此请使用onClickListener进行操作。按钮有效,但它不再改变它的风格。

我必须手动执行此操作吗?怎么样?

2 个答案:

答案 0 :(得分:0)

我们需要一个XML文件drawable选择器。我用res/drawable/bg_button.xml命名了这个文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_focused="true" android:drawable="@drawable/bg_button_pressed"/>
    <item android:state_pressed="true" android:drawable="@drawable/bg_button_pressed" />
    <item android:drawable="@drawable/bg_button_normal" />  <!-- normal state -->
</selector>

res/drawable/bg_button_pressed.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="color when pressed" />
</shape>

创建一个新的XML文件,将其命名为res/drawable/bg_button_normal.xml,然后复制上面的代码。然后,用正常颜色替换android:color,即当按钮处于正常状态时。

最后:

<Button
    android:id="@+id/..."
    android:text="@string/..."
    android:background="@drawable/bg_button"/>

如果您没有res/drawable文件夹,请创建一个新文件夹。

答案 1 :(得分:0)

试试这个,

  1. 参考按钮

    yourButton = (Button) <fragment name>.findViewById(R.id.<button id>);
    yourButton.setOnClickListener(this);
    
  2. 在您的点击事件中,

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    
    case R.id.yourButton:
        yourButton.setBackgroundColor(getActivity().getResources().getColor(<colour code>));
        break;
    
    default:
        break;
    }
    }
    
相关问题