java – 在OnCreate中定义Button – 无法解析方法中的符号

你会看到我是初学者.我无法看到我在哪里可以合法地放置Button语句和setText语句,所以这将编译.如果我移动一个,则另一个不起作用,反之亦然.我知道OnCreate是受保护的,所以“buttonOne”不会传递给playPhrases方法,但我现在已经改变了一段时间,但没有任何作用.请简单解释一下.

    package com.example.android.languageapp;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.button;

public class MainActivity extends AppCompatActivity {

    MediaPlayer myMediaPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myMediaPlayer = MediaPlayer.create(this, R.raw.hello);

        String[] phrases = getResources().getStringArray(R.array.phrase);



        Button buttonOne = (Button) findViewById(R.id.button1);
        Button buttonTwo = (Button) findViewById(R.id.button2);
        Button buttonThree = (Button) findViewById(R.id.button3);
        Button buttonFour = (Button) findViewById(R.id.button4);
        Button buttonFive = (Button) findViewById(R.id.button5);
        Button buttonSix = (Button) findViewById(R.id.button6);
        Button buttonSeven = (Button) findViewById(R.id.button7);
        Button buttonEight = (Button) findViewById(R.id.button8);

        buttonOne.setText(phrases[0]);
        buttonTwo.setText(phrases[1]);
        buttonThree.setText(phrases[2]);
        buttonFour.setText(phrases[3]);
        buttonFive.setText(phrases[4]);
        buttonSix.setText(phrases[5]);
        buttonSeven.setText(phrases[6]);
        buttonEight.setText(phrases[7]);
    }


    public void playPhrases(View clickedButton) {

        int id = clickedButton.getId();

        Log.i("Button id", "" + id);

        if (id == buttonOne.getId()) {

            myMediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);

            myMediaPlayer.start();
        }


    }



}

谢谢你的帮助

最佳答案 你只需在playPhrases中使用id点击这样的监听器,

public void playPhrases(View clickedButton) {

    int id = clickedButton.getId();

    Log.i("Button id", "" + id);

    switch (id) {
        case R.id.R.id.button1:
            // Button 1 operation
            myMediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);

            myMediaPlayer.start();
            break;
        case R.id.R.id.button2:
            // Button 2 operation
            break;
        case R.id.R.id.button3:
            // Button 3 operation
            break;
    }
    // We dont need button object
    //if (id == buttonOne.getId()) {
    //
    //    myMediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
    //
    //    myMediaPlayer.start();
    //}


}
点赞