2016-12-31 36 views
1

考慮的TabbedActivity這部分代碼:爲什麼片段之前叫過?

public class MainActivity extends AppCompatActivity { 

/** 
* The {@link android.support.v4.view.PagerAdapter} that will provide 
* fragments for each of the sections. We use a 
* {@link FragmentPagerAdapter} derivative, which will keep every 
* loaded fragment in memory. If this becomes too memory intensive, it 
* may be best to switch to a 
* {@link android.support.v4.app.FragmentStatePagerAdapter}. 
*/ 
private SectionsPagerAdapter mSectionsPagerAdapter; 

/** 
* The {@link ViewPager} that will host the section contents. 
*/ 
private ViewPager mViewPager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.container); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
    tabLayout.setupWithViewPager(mViewPager); 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 

} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

/** 
* A placeholder fragment containing a simple view. 
*/ 
public static class PlaceholderFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    private static final String ARG_SECTION_NUMBER = "section_number"; 

    public PlaceholderFragment() { 
    } 

    /** 
    * Returns a new instance of this fragment for the given section 
    * number. 
    */ 
    public static PlaceholderFragment newInstance(int sectionNumber) { 
     PlaceholderFragment fragment = new PlaceholderFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) 
    { 
     switch (getArguments().getInt(ARG_SECTION_NUMBER)) 
     { 
      case 1: 
       View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
       return rootView; 

      case 2: 
       View rootView2 = inflater.inflate(R.layout.fragment_main, container, false); 
       Toast.makeText(getContext(),"FRAGMENT 2 BUILT WHEN WE VIEW FRAGMENT 1! ",Toast.LENGTH_LONG).show(); 
       return rootView2; 

      case 3: 
       View rootView3 = inflater.inflate(R.layout.fragment_main, container, false); 
       return rootView3; 

      default: 
       View rootView0 = inflater.inflate(R.layout.fragment_main, container, false); 
       return rootView0; 
     } 
    } 
} 

/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the sections/tabs/pages. 
*/ 
public class SectionsPagerAdapter extends FragmentPagerAdapter { 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a PlaceholderFragment (defined as a static inner class below). 
     return PlaceholderFragment.newInstance(position + 1); 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     switch (position) { 
      case 0: 
       return "SECTION 1"; 
      case 1: 
       return "SECTION 2"; 
      case 2: 
       return "SECTION 3"; 
     } 
     return null; 
    } 
} 

}

當我們在案例1,箱體2被稱爲如果我把一個麪包,我想在第二個片段看,我第一次看它,因爲第二次是以前建造的。我只想在片段在TabbedActivity中可視化時調用片段的創建。我怎樣才能做到這一點?

+0

「當我們情況1,情況2被稱爲「呃?不要用Toast進行調試,學會使用logcat。 – weston

+0

@weston片段始終在視圖物理之前構建,例如,當我們查看片段編號1時,構建片段編號2.當我們在物理上查看片段時,我想構建片段編號2。您是否瞭解我? – Curio

+0

是什麼讓你認爲frag2在屏幕上出現碎片?在你的代碼中沒有任何證據證明它 –

回答

1

TabbedActivity在覈心中使用ViewPager提供滑動行爲。據我所知,你希望碎片只有在它變得可見時才被實例化。但是,默認情況下,ViewPager總是加載帶有1個預取項目的片段(或項目)。您可以更改該金額,但最低爲1。以下是ViewPager類的代碼:

public void setOffscreenPageLimit(int limit) { 
    if (limit < DEFAULT_OFFSCREEN_PAGES) { 
     Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " 
       + DEFAULT_OFFSCREEN_PAGES); 
     limit = DEFAULT_OFFSCREEN_PAGES; 
    } 
    if (limit != mOffscreenPageLimit) { 
     mOffscreenPageLimit = limit; 
     populate(); 
    } 
} 

因此,使用ViewPager無法達到目標。您可以使用TabLayout實施類似行爲

與TabLayout XML佈局:

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <android.support.v7.widget.Toolbar 
     android:layout_width="match_parent" 
     android:layout_height="?android:attr/actionBarSize" 
     android:background="@color/colorPrimary" 
     app:contentInsetStart="0dp"> 

     <android.support.design.widget.TabLayout 
      android:id="@+id/tabLayout" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      app:tabIndicatorColor="#000000" 
      app:tabIndicatorHeight="3dp"> 

      <android.support.design.widget.TabItem 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Tab 1" /> 

      <android.support.design.widget.TabItem 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Tab 2" /> 

      <android.support.design.widget.TabItem 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Tab 3" /> 

      <android.support.design.widget.TabItem 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Tab 4" /> 

     </android.support.design.widget.TabLayout> 
    </android.support.v7.widget.Toolbar> 

    <FrameLayout 
     android:id="@+id/fragmentContainer" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" /> 

</LinearLayout> 

您還應該設置NoActionBar主題這個活動

活動代碼:

public class TabbedActivity extends AppCompatActivity { 

    private SparseArrayCompat<Fragment> fragments = new SparseArrayCompat<>(); 

    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.tabbed_activity); 
     setTitle(""); 
     fragments.put(0, new Fragment()); //Here you need to instantiate your fragments 
     fragments.put(1, new Fragment()); // instead of new Fragment() 
     fragments.put(2, new Fragment()); // like new Tab1Fragment() 
     fragments.put(3, new Fragment()); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout); 
     tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 
       changeFragment(tab.getPosition()); 
      } 

      @Override 
      public void onTabUnselected(TabLayout.Tab tab) { 

      } 

      @Override 
      public void onTabReselected(TabLayout.Tab tab) { 

      } 
     }); 
     changeFragment(0); 
    } 

    private void changeFragment(int position) { 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     FragmentTransaction transaction = fragmentManager.beginTransaction(); 
     Fragment fragment = fragments.get(position); 
     String transactionTag = fragment.getClass().getSimpleName(); 
     if (fragmentManager.getBackStackEntryCount() > 0 && 
       fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName() 
         .equalsIgnoreCase(transactionTag)) { 
      return; 
     } 
     transaction.replace(R.id.fragmentContainer, fragment, transactionTag); 
     transaction.commitAllowingStateLoss(); 
    } 
} 

TabLayout很靈活,在這裏閱讀更多(https://guides.codepath.com/android/google-play-style-tabs-using-tablayout

+0

是的,你理解我!我怎樣才能像ViewPager一樣使用TabLayout? – Curio

+0

看,TabLayout不會給你ViewPager的完整行爲,因爲ViewPager總是使用預載來提供平滑的滑動。使用TabLayout,您將只能控制切換選項卡上的片段而不是滑動事件。它會爲您提供類似的用戶界面,但有點不同的互動 –

+0

我如何創建一個TabbedActivity的TabbedActivity? – Curio