使用同一个侦听器的多个活动
我有 4 个活动,它们都包含一个 xml 页脚,其中包含 4 个按钮(每个活动一个)。 我现在想为这些按钮设置 onclicklisteners (这是页脚中的自制菜单)。
问题是,如何使用侦听器以便重用代码? 我有两个想法:
创建一个实现 onclicklistener 的类,在每个活动中我都会获取按钮,然后创建侦听器类的新实例并执行 button.setOnClickListener(onClickListener) 问题是在侦听器类中,我如何检查哪个按钮调用了该事件? 我将如何创建启动活动的意图,通常我会这样做: Intent意图 = new Intent(FromActivity.this, ToAcitivty.class) 但我没有对 FromActivity 的引用。
创建一个从 Activity 扩展的基类,然后 4 个 Activity 将从该基类扩展。然后我想在基类中设置侦听器。这里的问题是我无法通过执行以下操作来获取对按钮的引用 按钮button1 = (Button)findViewById(R.id.menu_button1); Button1 将为空。我什至没有调用 setEventView,因为这应该在活动中完成,而不是在基类中完成。
有什么想法吗?
谢谢
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:
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.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.
Any ideas?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
相同的代码在这里:(
编辑为原始第一行在代码格式上被破坏。
Same code is here:
(edited as the original first line is broken on code format.