我有一个导航视图和绘制我的应用程序的布局,我使用片段之间切换视图。我现在有它实现这样的,它工作正常:Android更好地实现导航片段
app_bar_main.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
我设置的初始片段时,在我的MainActivity
类的onCreate
应用程序第一次启动:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//Provide global access to navigationview and toolbar
NavigationView navigationView = null;
Toolbar toolbar = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set initial fragment
NewFragment fragment = new NewFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
...
当用户选择一个菜单项时,我设置了这样的换出片段:
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_new) {
NewFragment fragment = new NewFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_start) {
StartFragment fragment = new StartFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
...
我觉得我在初始片段集以及if语句中有很多冗余代码
什么是更好的方式来压缩代码并换出片段而不会像这样重复?
加入片段,您可以添加getSupportFragmentManager()的BeginTransaction()。替换(R.id.fragment_container,new StartFragment()); –