我有一個導航視圖和繪製我的應用程序的佈局,我使用片段之間切換視圖。我現在有它實現這樣的,它工作正常: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()); –