簡體   English   中英

java.lang.IllegalStateException:在android:onClick屬性的父級或祖先上下文中找不到方法

[英]java.lang.IllegalStateException: Could not find method in a parent or ancestor Context for android:onClick attribute

我試圖將onClick方法front()到我的Button中。 但是,當我單擊按鈕時,它將返回此錯誤:

java.lang.IllegalStateException: Could not find method front(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'front'

這是我的xml:

<Button
    android:id="@+id/front"
    android:onClick="front"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text" />

Register.java:

public class Register extends AppCompatActivity {

    private Button front;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        front = (Button) findViewById(R.id.front);
    }

    private void front(View v) {
        Toast.makeText(Register.this, "String", Toast.LENGTH_LONG).show();
    }

}

知道是什么問題嗎?

在您的活動中,最重要的front method應該是公開的 您現在已將其設為私有。

Android Developer網站也對此進行了描述。

為了使它起作用,該方法必須是公共的並且接受View作為其唯一參數

public void front(View v) {
    Toast.makeText(Register.this, "String", Toast.LENGTH_LONG).show();
}

這就是通過活動向按鈕賦予點擊動作的方式。

front.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(this, "String", Toast.LENGTH_LONG).show();

            }
        });

要通過xml onClick按鈕操作,

public void front(View v) {
                Toast.makeText(this, "String", Toast.LENGTH_LONG).show();
}

確保正確編寫屬性值onClick的語法。 就我而言,我忘記了字符}

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    android:onClick="@{() -> viewModel.onItemClick(position)}">

GL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM