往容器中添加Fragment
第一步:布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>
第二步:MainActivity
package com.example.superapphomeui;
import android.os.Bundle;
import android.widget.FrameLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 容器
FrameLayout container = findViewById(R.id.container);
// 往容器中添加Fragment
FragmentManager supportFragmentManager = getSupportFragmentManager();
HomeV2Fragment fragment = new HomeV2Fragment();
String tag = "HomeV2Fragment";
supportFragmentManager.beginTransaction()
.add(R.id.container, fragment, tag)
.commit();
}
}
第三步:Fragment
package com.example.superapphomeui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class HomeV2Fragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_v2, container, false);
return view;
}
}