1.布局文件:
布局效果如下:
2.核心代码:
public class Main2Activity extends AppCompatActivity {
@BindView(R.id.tab)
TabLayout tab;
@BindView(R.id.nv)
NavigationView nv;
//集合添加Fragment:
private List list = new ArrayList<>();
//无阴影的图片:
int[] NotTabImage = new int[]{R.drawable.eat, R.drawable.baidu, R.drawable.send, R.drawable.aidl, R.drawable.ndk, R.drawable.thing};
//有阴影的图片:
int[] CheckedImage = new int[]{R.drawable.eat_press, R.drawable.baidu_press, R.drawable.send_press, R.drawable.aidl_press, R.drawable.ndk_press, R.drawable.thing_press};
//设置名字:
String[] name = new String[]{"Retrofit", "Baidu", "传感器", "aidl", "NDK", "分发事件"};
@BindView(R.id.bar2)
Toolbar bar2;
@BindView(R.id.vp)
ViewPager vp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ButterKnife.bind(this);
/**
* 一:设置bar:
*/
setSupportActionBar(bar2);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
/**
* 二、tabLayout连接ViewPager:
*/
tab.setupWithViewPager(vp);
/**
* 三、添加viewPager
*/
list.add(new Retrofit_one());
list.add(new Baidu_two());
list.add(new sendFeelThing_three());
list.add(new aidl_four());
list.add(new Ndk_five());
list.add(new Thing_six());
/**
* 四、适配TabLayout:
*/
FragmentHoder fragmentHoder = new FragmentHoder(getSupportFragmentManager(), this, list);
vp.setAdapter(fragmentHoder);
/**
* 五、滑动效果:
*/
tab.setTabMode(TabLayout.MODE_SCROLLABLE);
/**
* 六、添加文字+添加图片:
*/
for (int i = 0; i < tab.getTabCount(); i++) {
tab.getTabAt(i).setText(name[i]);
tab.getTabAt(i).setIcon(NotTabImage[i]);
}
//默认第一个图标是选中的:
tab.getTabAt(0).setIcon(CheckedImage[0]);
/**
* 七、实现选中的Tab突出显示:
*/
tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab1) {
//选中时显示的图标
tab.getTabAt(tab1.getPosition()).setIcon(CheckedImage[tab1.getPosition()]);
}
@Override
public void onTabUnselected(TabLayout.Tab tab1) {
//未选中时显示的图标
tab.getTabAt(tab1.getPosition()).setIcon(NotTabImage[tab1.getPosition()]);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
/**
* 八、设置NavigayionView点击事件:
*/
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
switch (itemId){
case R.id.one:
item.setChecked(true);
break;
case R.id.two:
item.setChecked(true);
break;
case R.id.three:
item.setChecked(true);
break;
case R.id.four:
item.setChecked(true);
break;
case R.id.five:
item.setChecked(true);
break;
}
return true;
}
});
}
}
侧边栏navigationview布局:
布局效果如下:
菜单menu的创建:
最终效果如下: