我是Android开发的新手。我想使用ViewPager
创建一个类似Activity
的标签。 Sample of app
我试过以下代码......
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
instantiateTab();
}
public void instantiateTab() {
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
final int[] ICONS = new int[]{
R.drawable.ic_chat_bubble_outline_black_24dp,
R.drawable.ic_search_black_24dp,
R.drawable.ic_library_add_black_24dp,
R.drawable.ic_notifications_none_black_24dp,
R.drawable.ic_person_outline_black_24dp,
};
tabLayout.getTabAt(0).setIcon(ICONS[0]);
tabLayout.getTabAt(1).setIcon(ICONS[1]);
tabLayout.getTabAt(2).setIcon(ICONS[2]);
tabLayout.getTabAt(3).setIcon(ICONS[3]);
tabLayout.getTabAt(4).setIcon(ICONS[4]);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (tabLayout.getSelectedTabPosition() == 0) {
startActivity(new Intent(DashboardActivity.this, MessageActivity.class));
finish();
} else if (tabLayout.getSelectedTabPosition() == 1) {
startActivity(new Intent(DashboardActivity.this, FindjobActivity.class));
finish();
} else if (tabLayout.getSelectedTabPosition() == 2) {
startActivity(new Intent(DashboardActivity.this, PostProjectActivity.class));
finish();
} else if (tabLayout.getSelectedTabPosition() == 3) {
startActivity(new Intent(DashboardActivity.this, NotificationActivity.class));
finish();
} else if (tabLayout.getSelectedTabPosition() == 4) {
startActivity(new Intent(DashboardActivity.this, SettingsActivity.class));
finish();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
MessageActivity
扩展到类的实例化选项卡中
activity_message.xml
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message2);
instantiateTab();
}
activity_message.xml
<LinearLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/contentMessage"
android:layout_weight="0"
android:orientation="vertical">
<include
layout="@layout/common_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>