Android 检查哪个活动加载片段
有没有办法检查哪个活动从片段中加载片段?我有一个用户配置文件片段,它是从两个不同的活动加载的,但只有一个传递了一个值,因此当从包中获取值时,当片段从没有传递值的活动加载时,会抛出一个nullpointerexception。或者是否有更好的方法将值传递到片段中,以便片段仅在从该特定活动加载时才能获取值?您只需在片段中执行此检查:Android 检查哪个活动加载片段,android,android-fragments,Android,Android Fragments,有没有办法检查哪个活动从片段中加载片段?我有一个用户配置文件片段,它是从两个不同的活动加载的,但只有一个传递了一个值,因此当从包中获取值时,当片段从没有传递值的活动加载时,会抛出一个nullpointerexception。或者是否有更好的方法将值传递到片段中,以便片段仅在从该特定活动加载时才能获取值?您只需在片段中执行此检查: if(getActivity() instanceof SomeActivity){ //do something } 如果您确定是哪个活动(然后从该活动调用方法),
if(getActivity() instanceof SomeActivity){
//do something
}
如果您确定是哪个活动(然后从该活动调用方法),还可以强制执行
getActivity()
调用。您可以定义两个静态方法(也称为静态工厂方法)它返回片段的实例,其中包含要与bundle一起传递的参数,如以下代码所示:
private static final String BUNDLE_VALUE_KEY = "value";
@NonNull
public static YourFragment newInstance() {
return new YourFragment();
}
@NonNull
public static YourFragment newInstance(@NonNull String yourValue) {
final YourFragment instance = new YourFragment();
final Bundle args = new Bundle();
args.putString(BUNDLE_VALUE_KEY,yourValue);
instance.setArguments(args);
return instance;
}
final Bundle args = getArguments();
if(args != null){
yourValue = args.getString(BUNDLE_VALUE_KEY,null);
}
在要传递值的活动中,您可以使用:
final YourFragment fragment = YourFragment.newInstance(value);
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
final YourFragment fragment = YourFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
在其他活动中
可以使用:
final YourFragment fragment = YourFragment.newInstance(value);
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
final YourFragment fragment = YourFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
在Fragment
的onCreate
方法中,您可以像下面的代码一样检查参数并初始化值:
private static final String BUNDLE_VALUE_KEY = "value";
@NonNull
public static YourFragment newInstance() {
return new YourFragment();
}
@NonNull
public static YourFragment newInstance(@NonNull String yourValue) {
final YourFragment instance = new YourFragment();
final Bundle args = new Bundle();
args.putString(BUNDLE_VALUE_KEY,yourValue);
instance.setArguments(args);
return instance;
}
final Bundle args = getArguments();
if(args != null){
yourValue = args.getString(BUNDLE_VALUE_KEY,null);
}
因此,如果您的片段
附加到传递数据的活动
,您将拥有它。如果片段
附加到其他活动
,您将获得初始值(在本例中为null
)
或者您可以检查活动
的实例,其中片段
被附加。(不是最佳做法)
也许,在片段中只需要两个newInstance()方法。一个有参数,另一个没有参数。之后,在片段的onCreate方法中,若已传递参数,则可以读取该参数。之后,在片段中只需检查所需的参数是否为null