簡體   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