如何在不同的 activity 调用上执行不同的功能?
How to perform different function on different activity call?
假设我有三个类:第一、第二和第三。
我实际上想做的是:
如果我从第一个调用 activity 第二个,那么我希望执行一些任务 1,如果我从第三个调用 activity 第二个,那么应该执行一些不同的任务 2。
我怎样才能做到这一点?
你可以传递一个带有一些标志的包,这样你就可以确定你是来自第一还是第三 activity。试试这个:
public final static String EXTRA_PARAMETERS = "com.example....."; //some name
//in first and third activities
Intent intent = new Intent(this, second.class);
intent.putExtra(EXTRA_PARAMETERS, params); //params could be an array or something to identify from which activity you are calling second an int could be too.
startActivity(intent);
// in second activity
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
try{
parameter = b.getParcelable(first.EXTRA_PARAMETERS); //you can do 2 of this and catch the one is not.
}catch(Exception e){};
try{
parameter = b.getParcelable(third.EXTRA_PARAMETERS);
}catch(Exception e){};
请初始化所有用作示例的变量。祝你好运!如果你不明白,请告诉我。
在启动Second
的意图中,放入一些Bundle
数据来标记这个意图是来自First
还是Third
。详细信息是 here。
如果我这样做,
// Constants.java
public static class Constants {
public static String BUNDLE_KEY_FROM = "_BUNDLE_KEY_FROM";
}
并且在First
和Third
中,
Intent intent = new Intent(this, Second.class);
intent.putExtra(Constants.BUNDLE_KEY_FROM, "First"); // or "Third"
startActivity(intent);
然后在Second.onCreate()
、
Bundle extras = getIntent().getExtras();
if (extras != null) {
// get data via the key
String val = extras.getString(Constants.BUNDLE_KEY_FROM);
if (val.equals("First") ) {
funcFirst();
}else if(val.equals("Third") ){
funcThird();
}
}
假设我有三个类:第一、第二和第三。
我实际上想做的是:
如果我从第一个调用 activity 第二个,那么我希望执行一些任务 1,如果我从第三个调用 activity 第二个,那么应该执行一些不同的任务 2。
我怎样才能做到这一点?
你可以传递一个带有一些标志的包,这样你就可以确定你是来自第一还是第三 activity。试试这个:
public final static String EXTRA_PARAMETERS = "com.example....."; //some name
//in first and third activities
Intent intent = new Intent(this, second.class);
intent.putExtra(EXTRA_PARAMETERS, params); //params could be an array or something to identify from which activity you are calling second an int could be too.
startActivity(intent);
// in second activity
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
try{
parameter = b.getParcelable(first.EXTRA_PARAMETERS); //you can do 2 of this and catch the one is not.
}catch(Exception e){};
try{
parameter = b.getParcelable(third.EXTRA_PARAMETERS);
}catch(Exception e){};
请初始化所有用作示例的变量。祝你好运!如果你不明白,请告诉我。
在启动Second
的意图中,放入一些Bundle
数据来标记这个意图是来自First
还是Third
。详细信息是 here。
如果我这样做,
// Constants.java
public static class Constants {
public static String BUNDLE_KEY_FROM = "_BUNDLE_KEY_FROM";
}
并且在First
和Third
中,
Intent intent = new Intent(this, Second.class);
intent.putExtra(Constants.BUNDLE_KEY_FROM, "First"); // or "Third"
startActivity(intent);
然后在Second.onCreate()
、
Bundle extras = getIntent().getExtras();
if (extras != null) {
// get data via the key
String val = extras.getString(Constants.BUNDLE_KEY_FROM);
if (val.equals("First") ) {
funcFirst();
}else if(val.equals("Third") ){
funcThird();
}
}