使用同一侦听器的几种活动 [英] Several activities using same listener

查看:76
本文介绍了使用同一侦听器的几种活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个活动,所有活动都包含一个xml-footer,其中包含4个按钮(每个活动一个). 我现在想为这些按钮设置onclicklistener(在页脚中是一个自制菜单).

I got 4 activites that all include a xml-footer which contains 4 buttons (one for each activity). I would now like to setup onclicklisteners to these buttons (it's a self made menu in the footer).

问题是,如何使用侦听器,以便可以重用代码? 我有两个想法:

The question is, how do I use listeners so that I can reuse code? I have two ideas:

  1. 创建一个实现onclicklistener的类,在每个活动中我都将获取按钮,然后创建侦听器类的新实例并执行button.setOnClickListener(onClickListener) 问题是在侦听器类中,我将如何检查哪个按钮称为事件? 以及我如何创建意图来开始一项活动,通常我会这样做: Intent intent = new Intent(FromActivity.this,ToAcitivty.class) 但是我没有对FromActivity的引用.

  1. Create a class that implements onclicklistener and in every activity i would get the buttons and then create a new instance of the listener class and do button.setOnClickListener(onClickListener) The problem is that in the listener class, how would i check which button called the event? And how would I create an intent to start an activity, usually i would do: Intent intent = new Intent(FromActivity.this, ToAcitivty.class) But i don't have the reference to FromActivity.

创建一个从活动扩展的基类,然后这四个活动将从该基类扩展.然后,我想在基类中设置侦听器.这里的问题是我无法通过执行以下操作获取按钮的引用 按钮button1 =(按钮)findViewById(R.id.menu_button1); button1将为空.我什至没有调用setEventView,因为这应该在活动中完成,而不是在基类中完成.

Create a base class that extends from activity and then the 4 activies will extend from the base class. I would then like to setup the listeners in the base class. The problem here is that i can't get the references to the buttons by doing Button button1 = (Button)findViewById(R.id.menu_button1); button1 will be null. I haven't even called setEventView because this should be done in the activity not in the base class.

有什么想法吗?

谢谢

推荐答案

相同的代码在这里:

    public class MyClass extends Activity implements View.OnClickListener{
        btnA=(Button)findViewById(R.id.btnA);
        btnA.setOnClickListener(this);
        btnB=(Button)findViewById(R.id.btnB);
        btnB.setOnClickListener(this);


    }
    @Override
    public void onClick(View v)
    {
        Button clickedButton = (Button) v;
        switch (clickedButton.getId())
        {
            case R.id.btnA:
                Intent regIntent = new Intent(Home.this,Registration.class);
                startActivityIfNeeded(regIntent, 1);
                break;
            case R.id.btnB:
                //Some code
                break;
        }
    }

(修改为第一行的原始代码格式.

(edited as the original first line is broken on code format.

这篇关于使用同一侦听器的几种活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆