FragMent-通过Arguments方法 跟activity通信
今天主要学习下通过Arguments,实现activity 给fragment传递数据。这个方法也是通过参数bundle来进行数据传输的
直接看如下代码
一,定义一个fragment,在oncreateView 中实现布局
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.detail_dialog, container, false); if (mView != null) { mTitleView = (TextView) mView.findViewById(R.id.title); mTimeView = (TextView) mView.findViewById(R.id.time); mDurationView = (TextView) mView.findViewById(R.id.duration); mPathView = (TextView) mView.findViewById(R.id.path); mFileSizeView = (TextView) mView.findViewById(R.id.filesize); //通过getArguments获得bundle数据 mTitleView.setText(getArguments().getString("mTitle","")); android.util.Log.e("zhangshuli", "+++++++"+getArguments().getString("mTitle","")); mPathView.setText(getArguments().getString("mData","")); mDurationView.setText(getArguments().getString("mDuration","")); // +MtkUtils.stringForTime(mHolder.mDuration)); mTimeView.setText(getArguments().getString("mDateTaken","")); //+MtkUtils.localTime(mHolder.mDateTaken)); mFileSizeView.setText(getArguments().getString("mFileSize","")); //+Formatter.formatFileSize(mContext, mHolder.mFileSize)); // setButton(BTN_OK, mContext.getString(android.R.string.ok), this); } else { return super.onCreateView(inflater, container, savedInstanceState); }
activity 中实现引用
private void showDetail(final ViewHolder mHolder) { String mTitle =""+mHolder.mTitle; String mData=""+mHolder.mData; String mDuration =""+MtkUtils.stringForTime(mHolder.mDuration); String mDateTaken =""+MtkUtils.localTime(mHolder.mDateTaken); String mFileSize =""+Formatter.formatFileSize(this, mHolder.mFileSize); mFragment=new DetailFragment(); mBundle =new Bundle(); fmFragmentManager=getFragmentManager(); mBundle.putString("mTitle", mTitle); mBundle.putString("mData", mData); mBundle.putString("mDuration", mDuration); mBundle.putString("mDateTaken", mDateTaken); mBundle.putString("mFileSize", mFileSize); android.util.Log.e("zhangshuli", "======"+mFileSize);
//通过setArguments给fragment传递数据 mFragment.setArguments(mBundle); fmFragmentManager.beginTransaction().replace(R.id.main,mFragment).commit(); }