繁体   English   中英

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

[英]android:onClick="@drawable/… does not update button onClick

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

XML片段:

  <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"/>

为了在单击按钮时更改按钮的背景,您需要为其提供选择器。

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"/>

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代码中调用一个函数,并以编程方式在该函数内部更改可绘制对象。 就像是:

在xml文件中:

android:onClick="changeBackground"

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

public void changeBackground(){
    Button button = (Button)findViewById(R.id.update_button);
    button .setBackgroundResource(R.drawable.btn_update_active_hdpi); 
}

PS:我还没有运行代码,但我希望您能理解我要说的话。 希望能有所帮助

您可以使用选择器来完成此操作。 在您的可绘制文件夹中创建一个新的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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM