0
我正試圖通過在標籤頁上從左向右滑動我的應用程序進行滾動。現在,應用程序可以通過滾動標籤欄來滾動選項卡,但我不知道如何爲整個應用程序實現滾動。如何使用TabLayout滾動片段?
主要活動:
public class MainActivity extends AppCompatActivity {
public static MainActivity instance;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private TabLayout allTabs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance=this;
getAllWidgets();
bindWidgetsWithAnEvent();
setupTabLayout();
}
public static MainActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.tabs);
}
private void setupTabLayout() {
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
allTabs.addTab(allTabs.newTab().setText("ONE"),true);
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
allTabs.addTab(allTabs.newTab().setText("TWO"));
}
private void bindWidgetsWithAnEvent()
{
allTabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
setCurrentTabFragment(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setCurrentTabFragment(int tabPosition)
{
switch (tabPosition)
{
case 0 :
replaceFragment(fragmentOne);
break;
case 1 :
replaceFragment(fragmentTwo);
break;
}
}
public void replaceFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="scrollable"
app:tabBackground="@color/colorPrimary"
app:tabTextColor="#FFFF"
app:tabSelectedTextColor="#FFFF"
/>
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>