将活动转换为接口会导致错误“无法转换......”

时间:2014-01-01 16:44:17

标签: android interface android-activity

我想知道如何发送第一个活动的参考资料' MainActivity'当我们从第二个活动中调用一个类OtherClass时。 MainActivity使用Intent调用SecondActivity,SecondActivity必须将MainActivity的引用发送到Otherclass,以便OtherClass将最终结果发送到MainActivity,如下所示:

public class ActA extends Activity implements OtherClass.MyInterface {
    //...
    //actA sends Intent to actB
}


public class ActB extends Activity {
    //send interface actA to otherClass 
    ActB actB = new otherClass( (OtherClass.MyInterface)ActA.class );//wrong: cannot cast from Class<ActA> to myInterface

    //or : actB = new ActB(arg1, ActA.class);//wrong: ask me to change the constructor of Otherclass



//constructor of otherclass
public OtherClass( OtherClass.MyInterface resultReceiver)

//in OtherClass 
public interface MyInterface {
    public void myFunc();
}

你知道如何解决这些错误吗?

1 个答案:

答案 0 :(得分:-1)

更新

我还没完全清楚。这是一个丑陋的解决方案,但它会回答你的问题

但我想你的问题需要 What you need is to set a listener that will get called when you process something asynchronously

简单

将单独的类保持为单身

示例:

public class singletonClass{

private yourInterface myInterface;
private singletonClass instance;

// Use this method to get the object of this class
public static singletonClass getInstance()
{
    if(instance == null)
        instance = new singletonClass();
    return instance;
}

public yourInterface getListener()
{
    return myInterface;
}

public void setListener(yourInterface listener)
{
    this.listener = listener;
}

}

现在来自您的ActivityA

singletonClass instance = singletonClass.getInstance();
instance.setListener(this);

确保您的ActivityA implements界面

然后从ActivityB

singletonClass instance = singletonClass.getInstance();
yourInterface listener = instance.getListener();

然后使用上面的listener

调用构造函数