1 静态创建
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.fragmenttest.fragment.StaticFragment"
/>
package com.example.fragmenttest.fragment;
import com.example.fragmenttest.MainActivity;
import com.example.fragmenttest.R;
public class StaticFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private TextView textView;
private RatingBar ratingBar;
private RadioButton radioButton;
@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) {
return inflater.inflate(R.layout.fragment_static, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = view.findViewById(R.id.tv_like);
ratingBar = view.findViewById(R.id.rb_bar);
radioButton = view.findViewById(R.id.rb_like);
radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setText("i like");
}
});
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
2 动态创建
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_fragment);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment2, DynamicFragment.class, null).commit();
}
<androidx.fragment.app.FragmentContainerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment2"
/>
|