[英]Button color wasn't changed after clicking
點擊按鈕顏色后,下面的代碼沒有改變。 我的代碼是->
public void onClick(View ButtonView){
ButtonView.setBackgroundColor(Color.RED);
Toast.makeText(this,"Clicked!",Toast.LENGTH_SHORT).show();
}
這是我從 Android studio-> --------- 崩潰開始的“運行”選項卡中得到的錯誤
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.helloworldapp, PID: 16093
java.lang.IllegalStateException: Could not find method Button(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.button.MaterialButton with id 'onClick'
這是我的“activity_main.xml”文件->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:onClick="onClick"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:onClick="@string/button"
android:text="@string/button" />
</LinearLayout>
在這里,我看到的錯誤是-> 找不到我的方法“onClick”。
但怎么可能?
“onClick”的原因沒有找到這個錯誤,我們沒有將點擊事件與相應的方法聯系起來。
android:onClick="onClick"
這將鏈接 Activity 中的onclick()
方法
Button
的onClick
屬性必須設置為您的活動 class 的點擊監聽器方法。
所以改變這個:
android:onClick="@string/button"
對此:
android:onClick="onClick"
Button myButton = findViewById(R.id.onClick);
public void onClick() {
myButton.setBackgroundColor(Color.RED);
Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show();
}
這應該有效。
你可以試試這個:[MainActivity.java][1] [1]: https://i.stack.imgur.com/OnI2h.png
[activity_main.xml][2][2]:https://i.stack.imgur.com/a7Rdh.png
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.