我試圖將一個對象從活動傳遞到滑動選項卡片段。我使用Bundle,Serializable和args的newInstance方法,但我的問題是如何以及應該在哪裏調用此方法。提前致謝。將Google API客戶端對象從活動傳遞到滑動選項卡片段
MainActivity
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient apiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_APPFOLDER)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
PageAdapter
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
ValidTab tab1 = new ValidTab();
return tab1;
case 1:
ExpiredTab tab2 = new ExpiredTab();
return tab2;
case 2:
AllTab tab3 = new AllTab();
return tab3;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
ValidTab
public class ValidTab extends Fragment {
DatabaseHelper db;
Button pick_buy_date, pick_exp_date, save, sync;
TextView buy_date, exp_date;
EditText et_name,et_shop,et_note;
int type;
private static final String DESCRIBABLE_KEY = "gapiclient";
private GoogleApiClient googleApiClient;
public static ValidTab newInstance(GoogleApiClient gApiclient){
ValidTab validTab = new ValidTab();
Bundle bundle = new Bundle();
bundle.putSerializable(DESCRIBABLE_KEY, (Serializable) gApiclient);
validTab.setArguments(bundle);
return validTab;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
googleApiClient = (GoogleApiClient) getArguments().getSerializable(DESCRIBABLE_KEY);
View rootView = inflater.inflate(R.layout.valid_tab, container, false);
return rootView;
}
現在檢查我的答案 –