80,349
社区成员
发帖
与我相关
我的任务
分享
public class ViewActivity extends AppCompatActivity {
private MainFragment mainFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
//实例化MainFragment
mainFragment = new MainFragment();
//将Fragment添加到container中
getSupportFragmentManager().beginTransaction().add(R.id.fl_container,mainFragment).commitAllowingStateLoss();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".Fragment.ViewActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="activity_view"
android:textSize="20dp"
android:id="@+id/tv_4"
android:textColor="#000"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/tv_4"
android:id="@+id/fl_container" />
</RelativeLayout>
public class MainFragment extends Fragment {
private TextView tv_3;
private View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.main_fragment,container,false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv_3 = (TextView) view.findViewById(R.id.tv_3);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="主页"
android:gravity="center"
android:textSize="50dp"
android:textColor="#000"
android:id="@+id/tv_3"/>
</LinearLayout>