如何在setOnClickListener中显示Toast?

时间:2018-04-20 21:49:11

标签: android

我正在尝试在用户点击“播放”按钮时显示Toast。但是makeText在我的代码中是红色的,它不会运行。我哪里错了?

这是Java代码:

    // Find the View that shows the play_a button
    ImageView play_a = findViewById(R.id.play_a);

    // Set a click listener on that View
    play_a.setOnClickListener(new View.OnClickListener() {
        // The code in this method will be executed when play_a is clicked on.
        Toast.makeText(this, "Sorry, Play doesn't work", Toast.LENGTH_LONG).show();
    });

我需要覆盖setOnClickListener的问题吗?

2 个答案:

答案 0 :(得分:2)

makeText 中的

OnClickListener关键字指的是Context类型的 anonymous-inner-class 。您需要更改它以传递play_a.getContext()

例如:extern crate serde; extern crate serde_json; fn main() { let the_file = r#"{ "FirstName": "John", "LastName": "Doe", "Age": 43, "Address": { "Street": "Downing Street 10", "City": "London", "Country": "Great Britain" }, "PhoneNumbers": [ "+44 1234567", "+44 2345678" ] }"#; let json: serde_json::Value = serde_json::from_str(the_file).expect("JSON was not well-formatted"); } 或您想要推介的方式。

答案 1 :(得分:1)

您必须覆盖onClick功能。

play_a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"Sorry, Play doesn't work", Toast.LENGTH_LONG).show();
        }
    });