I would like to record the learning process with articles, and please indicate if there are any mistakes.
foreword
This article will address two practical problems:
Activity
How to pass data toFragment
Fragment
How to pass data toActivity
Activity
Passing data to the object Activity
can be obtained by storing the data in the Intent
object, calling the sender, and calling Intent.putExtra()
the receiver getIntent().getXxx(getInt,getString,getBoolean等)
.
As Fragment
for Fragment
passing data to, in fact, it is Fragment1
to obtain the host Activity
reference, and then pass the data to Fragment2
. After solving the above two problems, I believe you will know how to deal with them.
Activity passes data to Fragment
In the Activity, obtain the instance of the corresponding fragment through the FragmentManager.findFragmentById(R.id.fragment_id) method, and then call the relevant method of the fragment to transfer the data.
There is a significant problem with this method, which will tightly bind the fragment and its host activity. We know that the introduction of Fragment is to use the UI more flexibly, which obviously loses flexibility, so we usually take the following steps the 2nd way.
To
Bundle
pass data as a medium: call a method
on宿主Activity
creation . Get the bundle containing the data by calling a method in . The advantage is: the decoupling of and is achieved .Fragment
Fragment.setArguments(bundle)
Fragment
Fragment.getArguments()
Fragment
Activity
Not much to say, go directly to the Demo:
- MainActivity.java
public class MainActivity extends AppCompatActivity {
//静态变量存储key,防止多处使用时输错
public static final String KEY = "key";
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//发送按钮初始化并设置点击事件
mButton = findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
//获取FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//实例化要添加的fragment
MyFragment fragment = new MyFragment();
//创建Bundle对象
Bundle args = new Bundle();
//添加数据
args.putString(KEY,"This is a message from Activity");
//将Bundle对象设置到fragment中
fragment.setArguments(args);
//动态添加fragment
fragmentTransaction.add(R.id.fragment_container,fragment).commit();
}
});
}
}
- MyFragment.java
public class MyFragment extends Fragment {
private TextView mTextView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//填充布局
View view = inflater.inflate(R.layout.fragment,container,false);
mTextView = view.findViewById(R.id.fragment_text);
//获取Activity传递过来的bundle对象
Bundle bundle = getArguments();
//获取某一值
String message = bundle.getString(MainActivity.KEY);
//显示传递值
mTextView.setText(message);
return view;
}
}
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|top"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is an Activity"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="Send Message"/>
<FrameLayout
android:layout_gravity="center"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
- fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#a90765">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I'm a fragment. And I receive a message that is: "/>
<TextView
android:id="@+id/fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:gravity="center"/>
</LinearLayout>
Results show:
So far, explain how to pass data from Activity to Fragment
Fragment passes data to Activity
There are several ways:
Call getActivity() directly in the Fragment to get the associated activity instance, and then call the method in the Activity through the instance to pass the data.
Obviously, this has the same problem as the first method of Activity passing data to Fragment mentioned above, both of which are bound together and lose flexibility. Therefore, this method is basically deprecated
By means of interface callback
, the reference of the object created by the class that implements a certain interface is assigned to the declared interface variable (actually, it is a transformation), and the interface method implemented by the object of the implementation class is called through the interface variable.
// 声明的回调接口变量
Callback callback;
//实现了Callback接口的类(MyActivity)所创建的对象的引用 赋给 声明的回调接口变量(callback)
callback = new MyActivity();
// 通过该接口变量(callback)调用 该实现类对象(MyActivity)实现的接口方法(initialize())
callback.initialize();
Without further ado, let's go to Demo:
- Callback interface ICallBack
public interface ICallback {
//该接口只有一个方法,用来传递一段字符串
void getMessage(String message);
}
- MainActivity.java
public class MainActivity extends AppCompatActivity implements ICallback {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.activity_text);
//获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
//获取FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//实例化要添加的fragment
MyFragment fragment = new MyFragment();
//动态添加fragment
fragmentTransaction.add(R.id.fragment_container,fragment).commit();
}
//实现接口方法,收到fragment传递过来的字符串后,更新TextView
@Override
public void getMessage(String message) {
mTextView.setText(message);
}
}
- MyFragment.java
public class MyFragment extends Fragment {
//声明一个接口变量
private ICallback mCallback;
private Button mButton;
//将关联的Activity的引用 赋给 声明的接口变量(也即转型)
@Override
public void onAttach(Context context) {
super.onAttach(context);
mCallback = (ICallback) context;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment,container,false);
//button的初始化和点击事件
mButton = view.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//通过接口变量调用实现类中实现的接口方法,传递一串字符串
mCallback.getMessage("Message: This is a message from fragment");
}
});
return view;
}
}
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|top"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is an Activity"
android:textSize="20dp"
/>
<TextView
android:id="@+id/activity_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20dp"
android:text="Ready to receive message"/>
<FrameLayout
android:layout_gravity="center"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
- fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#a90765">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I'm a fragment."/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="Send Message"/>
</LinearLayout>
Results display
So far, explain how to pass data from Fragment to Activity
Demo site
Github-whdalive:DemoActivity&Fragment
Summarize
- This article introduces Activity&Fragment communication in as much detail as possible.
- The author's level is limited, if there are any mistakes or omissions, please correct me.
- Next, I will also share the knowledge I have learned. If you are interested, you can continue to pay attention to the Android development notes of whd_Alive.
- I will share technical dry goods related to Android development from time to time, and look forward to communicating and encouraging with you.