首先,你需要一个托管服务活动,扩大在其相关布局文件具有的FrameLayout AppCompatActivity。然后你在onCreate方法膨胀的布局,并添加所需的片段:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_placeholder) != null) {
if (savedInstanceState != null) {
return;
}
// we are extending AppCompatActivity, so we need supportFragmentManager
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_placeholder, new ContentFragment()).commit();
}
}
}
将根据布局文件activity_main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_placeholder"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>`
现在你需要定义ContentFragment:
public class RecordFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_content, container, false);
}
}
的最后一步是我们的片段的布局文件,fragment_content
,包含一个Button:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
欲了解更多我们使用AppCompatActivity的原因,请阅读this answer。