1.通过Bundle来传值(推荐)
Bundle bundle = new Bundle();
bundle.putString("key", "你好啊");
BlankFragment blankFragment = new BlankFragment();
blankFragment.setArguments(bundle);
2.通过Activity中的public方法来传值(不推荐)
- 因为第一个Activity不是固定的,如果复用后,可能就不是MainActivity了,所以强转成MainActivity是有问题的。
MainActivity
package com.example.zhangyu.myapplication;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = new Bundle();
bundle.putString("key", "你好啊");
BlankFragment blankFragment = new BlankFragment();
blankFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fl_fragment, blankFragment);
fragmentTransaction.commit();
}
public String getData() {
String s = "hello";
return s;
}
}
BlankFragment
package com.example.zhangyu.myapplication;
import android.content.Context;
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 BlankFragment extends Fragment {
private TextView tvTest;
public BlankFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
tvTest = view.findViewById(R.id.tv_test);
return view;
}
String data;
@Override
public void onAttach(Context context) {
super.onAttach(context);
data = ((MainActivity) context).getData();
}
@Override
public void onStart() {
super.onStart();
if (isAdded()) {
final String s = getArguments().getString("key");
tvTest.append("\n" + s);
tvTest.append("\n" + data);
}
}
}