虽然不推荐这种方法,但是还是写出来了,简单的用也没有什么问题,不过还是建议大家使用接口回调。
Android开发-Fragment之间传值-1-AndroidStudio 不推荐
Android开发-Fragment之间传值-2-AndroidStudio 推荐
之前我们讲了,Fragment中调用父Activity中方法,进行Fragment切换。
Android开发-Fragment中调用父Activity中方法-AndroidStudio
http://blog.csdn.net/iwanghang/article/details/52450299
OneFragment.java:
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 切换到TwoFragment 带position参数 mainActivity.showTwoFragment(position); }MainActivity.java:
private int noTaskMark = -1; // 用于标记的int值
/** * 切换到TwoFragment 带position参数 */ public void showTwoFragment(int position) { if (!(fragmentAll instanceof TwoFragment)) { FragmentTransaction fragmentTransaction = getSupportFragmentManager() .beginTransaction(); //如果所有的fragment都不为空的话,把所有的fragment都进行隐藏。最开始进入应用程序,fragment为空时,此方法不执行 hideFragment(fragmentTransaction); //如果这个fragment为空的话,就创建一个fragment,并且把它加到ft中去.如果不为空,就把它直接给显示出来 if(twoFragment == null){ twoFragment = new TwoFragment(); fragmentTransaction.add(R.id.emptyFragment, twoFragment); }else { /** * 区别于 不带position参数的方法,这里需要移除Fragment,然后重新实例化,才可以setArguments */ //fragmentTransaction.show(twoFragment); fragmentTransaction.remove(twoFragment); twoFragment = new TwoFragment(); fragmentTransaction.add(R.id.emptyFragment, twoFragment); } /** * position */ Bundle bundle = new Bundle(); bundle.putInt("position", position); twoFragment.setArguments(bundle); //一定要记得提交 fragmentTransaction.commit(); } }
TwoFragment.java:
package com.iwanghang.fragmenttransactiondemo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class TwoFragment extends Fragment { private View view; private int position; private TextView twoFragmentText; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_two, container,false); twoFragmentText = (TextView) view.findViewById(R.id.twoFragmentText); position = getArguments().getInt("position"); if (position==-1){ twoFragmentText.setText("当前没有任务"); } if (position!=-1){ String positionString = String.valueOf(position); // int型 转换 String型 twoFragmentText.setText(positionString); } return view; } }