1 Fragment之间传递参数
FirstFragment中点击rl_changerole打开SecondFragment,并传递参数。
FirstFragment.java中部分代码:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_changerole:
SecondFragment crFragment = SecondFragment.newInstance(titleNames, titleType, parameter);
crFragment.setTargetFragment(PersonFragment.this, 0);
getFragmentManager().beginTransaction().replace(R.id.fl_content,crFragment)
.addToBackStack(null)
.commit();
break;
default:
break;
}
}
其实也可以不用调用SecondFragment的newInstance方法创建,通过以下这段代码实现,效果是一样的。
SecondFragment secondFragment = new SecondFragment();
Bundle args = new Bundle();
args.putStringArrayList("paramStr",titleNames);
args.putIntegerArrayList("paramInt",titleTypes);
args.putInt("knowcurrent",user.knowcurrent);
secondFragment.setArguments(args);
secondFragment.setTargetFragment(FirstFragment.this, 0);
getFragmentManager().beginTransaction().replace(R.id.fl_content,secondFragment)
.addToBackStack(null)
.commit();
SecondFragment.java类newInstance方法,在FirstFragment调用过。
public static SecondFragment newInstance(ArrayList titleNames, ArrayList titleTypes, int knowcurrent){
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
args.putStringArrayList("paramStr",titleNames);
args.putIntegerArrayList("paramInt",titleTypes);
args.putInt("param",parameter);
fragment.setArguments(args);
return fragment;
}
SecondFragment.java中获取FirstFragment传递过来的参数。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_changrole,container,false);
if(getArguments() != null){
titleNames = getArguments().getStringArrayList("paramStr");
titleTypes = getArguments().getIntegerArrayList("paramInt");
parameter= getArguments().getInt("param",-1);
}
return view;
}
private ArrayList titleNames;
private ArrayList titleTypes;
private int parameter;
2 Fragment返回上一个Fragment传回参数问题
2.1如果直接返回不需要传参数:
getFragmentManager().popBackStack();
2.2如果点击返回需要传回参数,在SecondFragment.java中通过以下实现。
rl_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendResult(Activity.RESULT_OK);
getFragmentManager().popBackStack();
}
});
sendResult方法
private void sendResult(int resultOk) {
if(getTargetFragment() == null){
return;
}else{
Intent i = new Intent();
i.putExtra("selectItem",selectItem);
getTargetFragment().onActivityResult(getTargetRequestCode(),resultOk,i);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != Activity.RESULT_OK){
return;
}else{
Integer str = data.getIntExtra("selectItem",-1);
System.out.println("selectItem---"+str);
}
}
参考网上资料,包括https://www.kancloud.cn/digest/android-lxj/138593但不限于此。
3 在Fragment启动Activity
Fragment类提供了startActivity方法,Fragment启动Activity类与Activity类启动另一个Activity类方法一样。