Android自写底部导航栏代码
时间: 2023-11-03 18:07:54 浏览: 75
下面是一个简单的Android自写底部导航栏的示例代码:
1. 首先在XML布局文件中添加底部导航栏的布局:
```
<LinearLayout
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:background="@color/colorPrimary">
<TextView
android:id="@+id/home_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:textColor="@android:color/white"
android:textSize="16sp"
android:layout_margin="8dp"/>
<TextView
android:id="@+id/search_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:textColor="@android:color/white"
android:textSize="16sp"
android:layout_margin="8dp"/>
<TextView
android:id="@+id/profile_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile"
android:textColor="@android:color/white"
android:textSize="16sp"
android:layout_margin="8dp"/>
</LinearLayout>
```
2. 在Java代码中为底部导航栏的每个按钮设置点击事件:
```
LinearLayout bottomNavigation = findViewById(R.id.bottom_navigation);
TextView homeButton = findViewById(R.id.home_button);
TextView searchButton = findViewById(R.id.search_button);
TextView profileButton = findViewById(R.id.profile_button);
homeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理Home按钮点击事件
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理Search按钮点击事件
}
});
profileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理Profile按钮点击事件
}
});
```
3. 在处理每个按钮的点击事件时,可以使用Fragment来切换不同的页面:
```
Fragment homeFragment = new HomeFragment();
Fragment searchFragment = new SearchFragment();
Fragment profileFragment = new ProfileFragment();
homeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, searchFragment).commit();
}
});
profileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, profileFragment).commit();
}
});
```
其中,`R.id.fragment_container`是一个用于显示Fragment的FrameLayout的ID,需要在XML布局文件中定义。例如:
```
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
这样,就可以通过点击底部导航栏的按钮来切换不同的页面了。
阅读全文
相关推荐

















