我必须将this
发送到另一个班级
在我的活动中我需要无效:
mStrawberry.foo(this)
和里面的草莓
public class Strawberry{
public Strawberry(){}
foo( ????? thisVariable ){
//work with this...
}
}
我知道这是MainActivity.this bud我不仅要使用不同的类MainActivity ...
感谢您的回复
答案 0 :(得分:2)
只需声明相应类型的参数(代码this
中的mStrawberry.foo(this)
除外):
public class Strawberry{
public Strawberry(){}
foo(TheRelevantType thisVariable ){ // ***
thisVariable.doSomething(); // ***
}
}
在上文中,我使用了TheRelevantType
。
我知道这是MainActivity.this bud我不仅要使用不同的类MainActivity ...
如果你需要一个接受两个不同类的实例的方法,你可以让两个类实现一个你需要使用的常见方面的接口:
interface ActivityCommon {
void doSomething();
}
class ThisActivity implements ActivityCommon {
public void doSomething() {
System.out.println("This is ThisActivity's doSomething");
}
}
class ThatActivity implements ActivityCommon {
public void doSomething() {
System.out.println("This is ThatActivity's doSomething");
}
}
class Strawberry {
foo(ActivityCommon common) {
common.doSomething();
}
}
...和/或使用一个看起来非常相似的公共基类:
class ActivityBase extends Activity { // Or whatever the base should be
abstract void doSomething();
}
class ThisActivity extends ActivityBase {
@Override
public void doSomething() {
System.out.println("This is ThisActivity's doSomething");
}
}
class ThatActivity extends ActivityBase {
@Override
public void doSomething() {
System.out.println("This is ThatActivity's doSomething");
}
}
class Strawberry {
foo(ActivityBase activity) {
activity.doSomething();
}
}
答案 1 :(得分:0)
我将展示Object的基本方法,因为您似乎不知道Java是如何工作的。你也可以使用泛型,但它会超越你的头脑,你会在实际理解它是如何工作之前犯错。
foo(Object passedActivity){
//Object is the base class to all classes in java and can refer to anything
if(passedActivity instanceof FirstActivity){
FirstActivity fref = (FirstActivity)passedActivity;
//modify the data now using fref
//fref.finish(); or any other similar thing
}else if(passedActivity instanceof SecondActivity){
SecondActivity sref=(SecondActivity)passedActivity;
//modify using sref now
//sref.finish(); or any other similar thing
}else{
Log.d("Error","Please pass a valid Activity");
}
}