导航栏(一)

导航栏(一)

TabLayout + Fragment

 布局文件

<?xml version="1.0" encoding="utf-8"?>
<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=".TabLayoutActivity">

<FrameLayout
android:id="@+id/home_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

<View android:layout_width="match_parent"
android:layout_height="0.5dp"
android:alpha="0.6"
android:background="@android:color/darker_gray"/>

<com.google.android.material.tabs.TabLayout
android:id="@+id/bottom_tab_layout"
android:layout_width="match_parent"
android:layout_height="50dp"
app:tabIndicatorHeight="0dp"
app:tabSelectedTextColor="@android:color/black"
app:tabTextColor="@android:color/darker_gray"/>


</LinearLayout>

3. 代码
public class TabLayoutActivity extends AppCompatActivity {
@BindView(R.id.bottom_tab_layout)
TabLayout mTabLayout;

private Fragment[]mFragmensts;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout);
ButterKnife.bind(this);
mFragmensts = DataGenerator.getFragments("TabLayout Tab");

initView();
}

private void initView() {
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
onTabItemSelected(tab.getPosition());

for (int i=0;i<mTabLayout.getTabCount();i++){
View view = mTabLayout.getTabAt(i).getCustomView();
ImageView icon = (ImageView) view.findViewById(R.id.tab_content_image);
TextView text = (TextView) view.findViewById(R.id.tab_content_text);
if(i == tab.getPosition()){
icon.setImageResource(DataGenerator.mTabResPressed[i]);
text.setTextColor(getResources().getColor(android.R.color.black));
}else{
icon.setImageResource(DataGenerator.mTabRes[i]);
text.setTextColor(getResources().getColor(android.R.color.darker_gray));
}
}


}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});

for(int i=0;i<4;i++){
mTabLayout.addTab(mTabLayout.newTab().setCustomView(DataGenerator.getTabView(this,i)));
}
}

private void onTabItemSelected(int position){
Fragment fragment = null;
switch (position){
case 0:
fragment = mFragmensts[0];
break;
case 1:
fragment = mFragmensts[1];
break;

case 2:
fragment = mFragmensts[2];
break;
case 3:
fragment = mFragmensts[3];
break;
}
if(fragment!=null) {
getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();
}
}
}

posted @   STDU_DREAM  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示