English 中文(简体)
你能为不同的按钮使用相同的OnClickListener吗?
原标题:Can you use the same OnClickListener for different buttons?

在android中,我可以为不同的按钮使用相同的OnClickListener吗?如果是,如何获取点击是从哪个按钮生成的?我目前有4个按钮,每个按钮都有自己的OnClickListener。每个OnClickListener都在做同样的事情,只是获取被点击按钮的文本。我想创建一个OnClickListener,但我不知道如何确定正在单击哪个按钮。非常感谢。

protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
                // TODO Auto-generated method stub

            }
        });
        setContentView(R.layout.home);
        Button button1 = (Button)findViewById(R.id.button1);
        Button button2 = (Button)findViewById(R.id.button2);
        Button button3 = (Button)findViewById(R.id.button3);
        Button button4 = (Button)findViewById(R.id.button4);

        //Load First Word
        button1.setOnClickListener(button1ClickListener);
        button2.setOnClickListener(button2ClickListener);
        button3.setOnClickListener(button3ClickListener);
        button4.setOnClickListener(button4ClickListener);

    }

不同部分用粗体表示的侦听器代码

private OnClickListener button1ClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        **Button button = (Button)findViewById(R.id.button1);**
        handleButtonClick(button);
    }
};

private OnClickListener button2ClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        **Button button = (Button)findViewById(R.id.button2);**
        handleButtonClick(button);

    }
};

private OnClickListener button3ClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        **Button button = (Button)findViewById(R.id.button3);**
        handleButtonClick(button);

    }
};

private OnClickListener button4ClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        **Button button = (Button)findViewById(R.id.button4);**
        handleButtonClick(button);

    }
};

手柄的代码Button click

private void handleButtonClick(Button button) {
        if(button.getText().equals(currentWord)){
            currentScore += availableScore;
            TextView score = (TextView)findViewById(R.id.textViewScore);
            score.setText(String.valueOf(score));
            currentIndex++;
            availableScore = 4;
            InitializeGame();
        }
        else{
            availableScore--;
            button.setEnabled(false);
        }
    }

根据Karthik的建议,我将代码修改为以下内容:

protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
                // TODO Auto-generated method stub

            }
        });
        setContentView(R.layout.home);
        Button button1 = (Button)findViewById(R.id.button1);
        Button button2 = (Button)findViewById(R.id.button2);
        Button button3 = (Button)findViewById(R.id.button3);
        Button button4 = (Button)findViewById(R.id.button4);

        //Load First Word
        button1.setOnClickListener(buttonClickListener);
        button2.setOnClickListener(buttonClickListener);
        button3.setOnClickListener(buttonClickListener);
        button4.setOnClickListener(buttonClickListener);

    }

OnClickListener代码

private OnClickListener buttonClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            handleButtonClick((Button)arg0);
        }
    };
最佳回答

是的,这是可能的。我在下面写了一个例子,应该是比较直接的。

像往常一样,为所有按钮添加OnClickListener,如下所示:

btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);

然后添加onClick()事件,如下所示:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v == btn1){
        //Things to do  
    }
    if(v == btn2){
        //Things to do      
    }
    if(v == btn3){
        //Things to do  
    } 
}

这应该很好用。不要忘记为onCreate所在的类实现View.OnClickListener,否则所有设置上面的OnClickListener的语句都将不正确。

问题回答
    protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

                @Override
                public void onInit(int arg0) {
                    // TODO Auto-generated method stub

                }
            });
            setContentView(R.layout.home);
            Button button1 = (Button)findViewById(R.id.button1);
            Button button2 = (Button)findViewById(R.id.button2);
            Button button3 = (Button)findViewById(R.id.button3);
            Button button4 = (Button)findViewById(R.id.button4);

            //Load First Word
            button1.setOnClickListener(button1ClickListener);
            button2.setOnClickListener(button2ClickListener);
            button3.setOnClickListener(button3ClickListener);
            button4.setOnClickListener(button4ClickListener);

        }

    @Override
        public void onClick(View v)

    {

    int id = v.getId();
    switch (id) {  
    case R.id.button1:  
    //your code
    break;
 case R.id.button2:  

    break;
 case R.id.button3:  

    break;
    }
    }




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签