setonclicklistener在另一个活动上 [英] setonclicklistener on another activity

查看:135
本文介绍了setonclicklistener在另一个活动上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个活动:"A"和"B".

Say I have two activities: "A" and "B".

活动A的布局中有一个按钮.我想将其设置为活动B的点击监听器实现. 假设这里是活动A:

Activity A has a button in it's layout. and I want to set it's click listener implemention on Activity B. So let's say here's Activity A:

Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(B.this);

在活动B中,我正在尝试实现该功能:

and in Activity B, I'm trying to implement the function:

public void OnClick(View v)
{
//DO SOMETHING
}

我遇到以下错误:

视图类型中的方法setOnClickListener(View.OnClickListener) 不适用于参数(A)

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (A)

  • 在作用域中无法访问类型A的封闭实例

我在这里做什么错了?

推荐答案

GUI组件的处理必须在实例化该UI的同一UI线程中进行.

The handling of the GUI components must be accompanied within the same UI thread that instantiated that.

因此您所需的视图不正确,还请确保只有在该视图设置了该组件且该视图当前可见(在前景中)时,您才能操作click和其他侦听器用户进行互动.

So your desired view is not correct also make sure the you can have the click and other listener been worked only if the view is set with that components and is currently visible ( In foreground) for the user to have interaction.

如果您确实希望这样做,则可以通过以下操作覆盖不同活动中点击侦听器的默认实现:

If you really want that then You can override the default implementation of the click listener within the different activities via following:

1)静态参考:在活动A中将按钮设为公共静态,并在活动B中以类A的名称使用该按钮.

1)Static Reference: make the button as public static in activity A and use it in Activity B by Class A's name.

2)接口:在活动A上实现OnClickListener,但在B中将无法访问

2)Interface:implements OnClickListener on the activity A , but will not be accessible in B

3)为所有活动自定义MyClickListener .

public class MyClickListener implements OnClickListener {
    @Override
    public void onClick(View v) {
        mContext = v.getContext();

        switch (v.getId()) {
case R.id.button:
// Your click even code for all activities
break;
default:
break; }}
}

使用A和B类,如下所示: 按钮button =(Button)findViewById(R.id.button); button.setOnClickListener(new MyClickListener());

Use it the class A and B both as shown below: Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new MyClickListener());

这篇关于setonclicklistener在另一个活动上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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