例如,在activity_main.xml中可以添加一个FrameLayout来作为fragment的容器:
例如,新建一个MyFragment类,继承自Fragment,并重写onCreateView方法:
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
//初始化控件,设置事件监听等
return rootView;
}
}
例如,在MainActivity中加载MyFragment:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//加载MyFragment
MyFragment fragment = new MyFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment).commit();
}
}