点击后java按钮的颜色没有改变

px9o7tmv  于 2021-07-03  发布在  Java
关注(0)|答案(5)|浏览(352)

点击按钮后,颜色并没有被下面的代码改变。我的代码是->

public void onClick(View ButtonView){
    ButtonView.setBackgroundColor(Color.RED);
    Toast.makeText(this,"Clicked!",Toast.LENGTH_SHORT).show();
}

这是我的错误,我从android studio中的“run”选项卡得到的->

v09wglhw

v09wglhw1#

崩溃开始

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\u 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”没有找到。
但怎么可能呢?

r1zk6ea1

r1zk6ea12#

Button myButton = findViewById(R.id.onClick);

public void onClick() {
    myButton.setBackgroundColor(Color.RED);
    Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show();
}

这应该管用。

tpgth1q7

tpgth1q73#

这个 onClick 的属性 Button 必须设置为活动类的click listener方法。
所以改变这个:

android:onClick="@string/button"

对此:

android:onClick="onClick"
9jyewag0

9jyewag04#

找不到“onclick”的原因此错误,我们没有将click事件与相应的方法链接。

android:onClick="onClick"

这将链接 onclick() 活动中的方法

r8xiu3jd

r8xiu3jd5#

您可以尝试以下方法:[mainactivity.java][1][1]:https://i.stack.imgur.com/oni2h.png
[活动\u main.xml][2][2]:https://i.stack.imgur.com/a7rdh.png

相关问题