各位看官们大家好,上一回中咱们说的是Android中Fragment之间数据传递的例子,这一回咱们继续说该例子。闲话休提,言归正转。让我们一起Talk Android吧!
看官们,本章回是Fragment之间的数据传递大结局,和以往一样我们将列出完整的代码,代码中包含了前面章回中所有的内容,不过没有按照章节进行区分,大家可以结合具体章节中的文字来分析代码,相信这个难不倒各位看官。下面是完整请大家参考。
package com.example.talk8.blogappall;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
//介绍Activity之间,以及Fragment之间的交互和数据传递
public class ActivityA extends AppCompatActivity
implements FragmentB.OnFragmentInteractionListener,
FragmentA1.OnFragmentInteractionListener1{
private Button mBtStartActB;
private Button mBtStartActBForData;
private Button mButtonF1ToF2;
private Button mButtonF2ToF1;
private Intent mIntent = null;
private int REQUEST_CODE = 1;
public static final String KEY = "value_key";
private static final String TAG = "DataStorage";
private FragmentA1 mFragmentA1;
private FragmentA2 mFragmentA2;
private FragmentB mFragmentB;
private FragmentManager mFragmentManager;
private android.support.v7.widget.Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
mBtStartActB =(Button)findViewById(R.id.start_activity_b);
mBtStartActBForData =(Button)findViewById(R.id.start_activity_b_for_data);
mBtStartActB.setOnClickListener(v -> startActivityB());
mBtStartActBForData.setOnClickListener(v->startActivityBForData());
mButtonF1ToF2 = (Button)findViewById(R.id.fraga1_to_a2);
mButtonF2ToF1 = (Button)findViewById(R.id.fraga2_to_a1);
// mFragmentA1 = new FragmentA1();
// mFragmentA2 = new FragmentA2();
//使用参数来创建Fragment对象
mFragmentA1 = FragmentA1.newInstance("FragmentA1","Data1");
mFragmentA2 = FragmentA2.newInstance("FragmentA2","Data2");
mFragmentManager = getSupportFragmentManager();
mFragmentManager.beginTransaction().replace(R.id.frag_a1,mFragmentA1).commit();
mFragmentManager.beginTransaction().replace(R.id.frag_a2,mFragmentA2).commit();
mButtonF1ToF2.setOnClickListener(v ->Frag1transferDataToFrag2());
mButtonF2ToF1.setOnClickListener(v ->Frag2transferDataToFrag1());
}
private void startActivityB() {
int value = 5;
if(mIntent != null)
mIntent = null;
//send Data to ActivityB
mIntent = new Intent(ActivityA.this,ActivityB.class);
mIntent.putExtra(KEY,value);
startActivity(mIntent);
Log.i(TAG, "startActivityB and send Data: "+value);
}
//want to get data from ActivityB
private void startActivityBForData() {
if(mIntent != null)
mIntent = null;
mIntent = new Intent(ActivityA.this,ActivityB.class);
startActivityForResult(mIntent,REQUEST_CODE);
Log.i(TAG, "startActivityB For getting Data: ");
}
//get data from ActivityB
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//注意:确认数据来源
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
int result = data.getExtras().getInt(KEY);
Log.i(TAG, "onActivityResult: ActivityA get data from ActivityB : "+result);
mFragmentA1.changeText(String.valueOf(result));
mFragmentA2.changeText(String.valueOf(result));
}else {
Log.i(TAG, "onActivityResult: it is not a effective data");
}
}
private void Frag1transferDataToFrag2() {
FragmentA2 fragmentA2 = (FragmentA2) mFragmentManager.findFragmentById(R.id.frag_a2);
fragmentA2.getData("FragmentA1 send data");
}
private void Frag2transferDataToFrag1() {
FragmentA1 fragmentA1 = (FragmentA1) mFragmentManager.findFragmentById(R.id.frag_a1);
fragmentA1.getData("FragmentA2 send data");
}
@Override
protected void onResume() {
super.onResume();
//使用Fragment的公有方法来传递数据,真正传递数据的操作在CallBack:onFragmentInteraction
mFragmentA1.onButtonPressed(null);
mFragmentB.onButtonPressed(null);
//验证数据是否传递成功
mFragmentA1.getDataFromParam();
mFragmentA2.getDataFromParam();
mFragmentB.getDataFromParam();
}
@Override
public void onFragmentInteraction(Uri uri) {
Log.i(TAG, "onFragmentInteraction: ");
mFragmentA2 = FragmentA2.newInstance("onFragmentInteraction","Data2");
mFragmentB = FragmentB.newInstance("onFragmentInteraction","DataB");
}
@Override
public void onFragmentInteraction1(Uri uri) {
Log.i(TAG, "onFragmentInteraction1: ");
mFragmentA2 = FragmentA2.newInstance("onFragmentInteraction1","Data2");
mFragmentB = FragmentB.newInstance("onFragmentInteraction1","DataB");
}
}
package com.example.talk8.blogappall;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class ActivityB extends AppCompatActivity
implements FragmentB.OnFragmentInteractionListener {
private static final String TAG = "DataStorage";
private Intent mIntent;
private int value;
private FragmentManager mFragmentManager;
private FragmentB mFragmentB ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
mFragmentB = new FragmentB();
mFragmentManager = getSupportFragmentManager();
mFragmentManager.beginTransaction().replace(R.id.frag_b,mFragmentB).commit();
//get data from ActivityA
mIntent = getIntent();
if(mIntent != null ) {
if (mIntent.hasExtra(ActivityA.KEY)) {
//get data from ActivityA
value = mIntent.getIntExtra(ActivityA.KEY,0);
if(value != 0) {
Log.i(TAG, "onCreate: ActivityB get Data from ActivityA: "+value);
// 不能在onCreate函数中使用,因为此时onCreateView还没有执行,textView为null
//mFragmentB.changeText(String.valueOf(value));
}else {
Log.i(TAG, "onCreate: ActivityB get Data is null");
}
} else {
//send data to ActivityA
value = 9;
Log.i(TAG, "onCreate: ActivityB send Data: "+value+" to ActivityA ");
mIntent = null;
mIntent = new Intent();
mIntent.putExtra(ActivityA.KEY,value);
setResult(RESULT_OK,mIntent);
}
}
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume: chage value; "+value);
mFragmentB.changeText(String.valueOf(value));
mFragmentB.getDataFromParam();
}
@Override
public void onFragmentInteraction(Uri uri) {
Log.i(TAG, "onFragmentInteraction: ");
}
}
package com.example.talk8.blogappall;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
// * {@link FragmentA1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FragmentA1#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentA1 extends Fragment {
private static final String TAG = "FragmentA1 DataStorage";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView mTextView;
private OnFragmentInteractionListener1 mListener;
public FragmentA1() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentA1.
*/
// TODO: Rename and change types and number of parameters
public static FragmentA1 newInstance(String param1, String param2) {
FragmentA1 fragment = new FragmentA1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_fragment_a1, container, false);
mTextView = (TextView)view.findViewById(R.id.fraga1_tv);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
Log.i(TAG, "onButtonPressed: ");
mListener.onFragmentInteraction1(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener1) {
mListener = (OnFragmentInteractionListener1) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener1 {
// TODO: Update argument type and name
void onFragmentInteraction1(Uri uri);
}
public void getData(String str) {
Log.i(TAG, "Fragment A1 getData: "+str);
}
public void changeText(String str) {
if(mTextView != null && str != null) {
Log.i(TAG, "FragmentA1 changeText: "+str);
mTextView.setText(str);
}
}
public void getDataFromParam() {
if(getArguments() != null){
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
Log.i(TAG, "getDataFromParam: "+mParam1+" "+mParam2);
}
}
}
package com.example.talk8.blogappall;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
// * {@link FragmentA2.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FragmentA2#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentA2 extends Fragment {
private static final String TAG = "FragmentA2 DataStorage";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView mTextView;
// private OnFragmentInteractionListener mListener;
public FragmentA2() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentA2.
*/
// TODO: Rename and change types and number of parameters
public static FragmentA2 newInstance(String param1, String param2) {
FragmentA2 fragment = new FragmentA2();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_fragment_a2, container, false);
mTextView = view.findViewById(R.id.fraga2_tv);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
// public void onButtonPressed(Uri uri) {
// if (mListener != null) {
// mListener.onFragmentInteraction(uri);
// }
// }
// @Override
// public void onAttach(Context context) {
// super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
// }
// @Override
// public void onDetach() {
// super.onDetach();
// mListener = null;
// }
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
// public interface OnFragmentInteractionListener {
// // TODO: Update argument type and name
// void onFragmentInteraction(Uri uri);
// }
public void getData(String str) {
Log.i(TAG, "Fragment A2 getData: "+str);
}
public void changeText(String str) {
if(mTextView != null && str != null) {
Log.i(TAG, "FragmentA2 changeText: "+str);
mTextView.setText(str);
}
}
public void getDataFromParam() {
if(getArguments() != null){
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
Log.i(TAG, "getDataFromParam: "+mParam1+" "+mParam2);
}
}
}
package com.example.talk8.blogappall;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
// * {@link FragmentB.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FragmentB#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentB extends Fragment {
private static final String TAG = "FragmentB DataStorage";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView mTextView;
private OnFragmentInteractionListener mListener;
public FragmentB() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentB.
*/
// TODO: Rename and change types and number of parameters
public static FragmentB newInstance(String param1, String param2) {
FragmentB fragment = new FragmentB();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i(TAG, "onCreateView: ");
View view = inflater.inflate(R.layout.fragment_fragment_b, container, false);
mTextView = (TextView)view.findViewById(R.id.fragb_tv);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
Log.i(TAG, "onButtonPressed: ");
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void changeText(String str) {
if(mTextView != null && str != null) {
Log.i(TAG, "FragmentB changeText: "+str);
mTextView.setText(str);
}
if(mTextView == null)
Log.i(TAG, "changeText: textView is null");
}
public void getDataFromParam() {
if(getArguments() != null){
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
Log.i(TAG, "getDataFromParam: "+mParam1+" "+mParam2);
}else {
Log.i(TAG, "getDataFromParam: param is null");
}
}
}
各位看官,关于Android中Fragment之间数据传递的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!