android:onClick =“@ drawable / ...不会更新按钮onClick

时间:2013-07-25 19:44:47

标签: java android xml onclick buttonclick

我正在尝试在单击按钮时更新按钮的图像,但是我在XML文件中使用的方法似乎没有创建所需的效果(或根本没有创建任何效果)。

XML SNIPPET:

  <Button
      android:id="@+id/update_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/update_text"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="90dp"
      android:background="@drawable/btn_update_inactive_hdpi" 
      android:onClick="@drawable/btn_update_active_hdpi"/>

3 个答案:

答案 0 :(得分:3)

为了在点击按钮时改变按钮的背景,你需要给它一个选择器。

<强> btn_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn_update_active_hdpi" android:state_pressed="true"></item>
    <item android:drawable="@drawable/btn_update_inactive_hdpi"></item>
</selector>

在你的布局中:

<Button
     android:id="@+id/update_button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@+id/update_text"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="90dp"
     android:background="@drawable/btn_selector"/>

答案 1 :(得分:1)

android:onClick调用方法。根据文件:

android:onClick

Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).

因此,尝试在按钮单击时和Java代码中调用函数,并在该函数内以编程方式更改drawable。类似的东西:

在xml文件中:

android:onClick="changeBackground"

在您的代码(设置此xml文件视图的活动)中,声明以下dunction:

public void changeBackground(){
    Button button = (Button)findViewById(R.id.update_button);
    button .setBackgroundResource(R.drawable.btn_update_active_hdpi); 
}
P.S:我没有运行代码,但我希望你能理解我想说的话。希望有所帮助

答案 2 :(得分:0)

您只需使用选择器即可完成此操作。在drawable文件夹中创建一个新的XML,并将其命名为“btn_background.xml”,并添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:drawable="@drawable/btn_update_active_hdpi" android:state_selected="true"></item>
  <item android:drawable="@drawable/btn_update_active_hdpi" android:state_pressed="true"></item>
  <item android:drawable="@drawable/btn_update_inactive_hdpi"></item>

</selector>

然后设置按钮的背景

android:background="@drawable/btn_background"

onClick属性用于将Activity的java方法中的方法分配给按钮。 (这基本上就像执行button.setOnClickListener()。)如果要设置onClick侦听器,则可以执行以下操作:

在XML

android:onClick="NameOfMethod"

在Java活动中

public void NameOfMethod(View v){
  //Do Click Stuff Here
}