Fragment进阶补充&viewpager
关于Fragment传值
1.Activity给Fragment传值
Activity:
public class Activity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a_2_f);
editText = findViewById(R.id.et_id);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.linear_layout_id,new ShowContextFragment());
fragmentTransaction.commit();
}
public void click(View view) {
//取到输入的值
String string = editText.getText().toString();
//创建fragment对象
ShowContextFragment showContextFragment = new ShowContextFragment();
//创建bundle
Bundle bundle = new Bundle();
bundle.putString("key",string);
//给fragment对象赋值
showContextFragment.setArguments(bundle);
//动态修改fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.linear_layout_id,showContextFragment);
fragmentTransaction.commit();
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".A2FActivity">
<EditText
android:id="@+id/et_id"
android:hint="来啊,传点啥吧!"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我试试"
android:onClick="click"
/>
<LinearLayout
android:orientation="horizontal"
android:id="@+id/linear_layout_id"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</LinearLayout>
Fragment:
public class ShowContextFragment extends Fragment {
private TextView textView;
public ShowContextFragment() {
// Required empty public constructor
}
//现在text里面的值是"hello_blank_fragment",思路就是拿到控件,重新赋值即可.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_show_context, container, false);
//1 拿控件
textView = inflate.findViewById(R