我只是尝试使用TabLayout,但遇到一些问题以了解其工作方式。碎片对我来说也是新的。这就是重点,用户启动应用程序时的第一个活动是教程。我在本教程的每一部分使用一个片段。而且,我知道只有视图分页器足以满足我只想在选项卡布局中尝试的用户。因此,在第一个片段中,我有一个TextView和一个Button。当用户单击按钮时,我想切换到教程第二部分的第二个选项卡,等等。
现在是第一个片段:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ext="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_tuto_first_fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_width="130dp"
android:layout_height="53dp"
android:id="@+id/valider_tuto_first_fragment"/>
</RelativeLayout>
Java文件:
public class TutoFirstFragment extends Fragment {
public TutoFirstFragment()
{
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.tuto_first_fragment, container, false);
}
}
活动上名为Tutoriel的onCreate()方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
replaceContentLayout(R.layout.tutorial_activity, super.CONTENT_LAYOUT_ID);
toolbar = (Toolbar) findViewById(R.id.tutorial_toolbar);
navigationView = (NavigationView) findViewById(R.id.nav_view);
tabLayout = (TabLayout) findViewById(R.id.tuto_tab_layout);
tabHost = (TabHost) findViewById(R.id.tuto_first_fragment_tabhost);
viewPager = (ViewPager) findViewById(R.id.tuto_view_pager);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(context, R.color.white));
toSecondFragment = (Button) findViewById(R.id.valider_tuto_first_fragment);
toSecondFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tabHost.setCurrentTab(tabLayout.getSelectedTabPosition() + 1);
}
});
}
问题在于,我无法在活动中创建onClickListener,而且我不了解如何分段进行。
多谢您与我分享您的知识:)
使您的片段实现OnClickListener
:
public class MainFragment extends Fragment implements OnClickListener
然后onClick
在您的片段中实现该方法
@Override // LISTENER
public void onClick(View v) { do your stuff there }
现在要将其侦听器分配给一个对象,请使用以下命令:
yourWhateverObject.setOnClickListener(this);
现在,如果您可以访问寻呼机,则可以在其中切换标签位置:
pager.setCurrentItem(position);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句