android - 如何添加BottomAppBar
问题描述
如何将 BottomAppBar 添加到我的 Main_Activity 布局中,如下所示:
我在 activity_main xml 中使用 content_main xml include layout="@layout/content_main" 只需要 2 个图标 1-home & 2-download
我尝试了很多方法但仍然无法正常工作导致应用程序崩溃
非常感谢
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.free.music.downloader.activity.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/content_main" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<include layout="@layout/activity_download" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="gone">
<include layout="@layout/ll_play_music" />
</LinearLayout>
content_main.xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorBlue"
android:orientation="horizontal">
<ImageView
android:id="@+id/img_option"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="15dp"
android:src="@drawable/menu"
app:tint="@color/colorWhite" />
<TextView
android:id="@+id/tv_download_intent"
style="?android:attr/textAppearanceMedium"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:gravity="center"
android:text="Music Downloader"
android:textColor="@color/colorWhite"
android:textStyle="bold" />
<ImageView
android:id="@+id/img_downloaded"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:padding="15dp"
android:src="@drawable/music_library" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorBlue">
<RelativeLayout
android:id="@+id/rl_search_song"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:background="@drawable/custom_ll_download"
android:orientation="horizontal">
<TextView
android:id="@+id/edt_link"
style="?android:textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:hint="@string/hint_search"
android:paddingLeft="20dp"
android:singleLine="true" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:src="@drawable/ic_search_ic"
app:tint="@color/colorBlue" />
</RelativeLayout>
</LinearLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp"
android:orientation="vertical">
<TextView
style="?android:textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="@string/hot_songs"
android:textColor="@color/colorBlack"
android:textStyle="bold">
</TextView>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/lv_hot_songs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
app:adSize="BANNER"
app:adUnitId="@string/ads_banner">
</com.google.android.gms.ads.AdView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
style="?android:textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="@string/het_key"
android:textColor="@color/colorBlack"
android:textStyle="bold">
</TextView>
<include layout="@layout/item_sugesstion_tag" />
</LinearLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterMusicSearch.ClickCallBack {
private Random random;
private final String[] PERMISSION_LIST = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private ArrayList<String> arrKey = new ArrayList<>();
public static final String HOT_SONGS_TITLE = "HOT_SONGS_TITLE";
public static final String HOT_SONGS_ID = "HOT_SONGS_ID";
public static final String CHECK_FIRST = "checkFirst";
private TextView tvDownloadIntent;
private AdapterMusicSearch adapterMusicSearch;
private ArrayList<Song> arrHotSongs = new ArrayList<>();
private SharedPreferences checkFirst;
private ImageView imgDownloaded, imgOption;
private ImageView imgPlayAndPause;
private RelativeLayout rlSearch;
private RecyclerView lvHotSongs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
adView.loadAd(adRequest);
if (!checkPermissionAvailable()) {
return;
}
initViews();
}
private boolean checkPermissionAvailable() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (String p : PERMISSION_LIST) {
if (checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(PERMISSION_LIST, 0);
return false;
}
}
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (checkPermissionAvailable()) {
initViews();
} else {
finish();
}
}
public String randomKey() {
return this.arrKey.get(new Random().nextInt(this.arrKey.size()));
}
public void initViews() {
addKeyYoutube();
checkFirst = getSharedPreferences(CHECK_FIRST, MODE_PRIVATE);
if (checkFirst.getString(CHECK_FIRST, "").equals("") || checkFirst.getString(CHECK_FIRST, "") == null) {
checkFirst.edit().putString(CHECK_FIRST, "1").commit();
} else if (checkFirst.getString(CHECK_FIRST, "").equals("1")) {
random = new Random();
int x = random.nextInt(3);
Log.e("asdfasdfa", x + "");
if (x == 1) {
showDialogRating();
}
} else {
Log.e("asdfadfadf", checkFirst.getString(CHECK_FIRST, ""));
}
rlSearch = findViewById(R.id.rl_search_song);
rlSearch.setOnClickListener(this);
imgPlayAndPause = findViewById(R.id.img_play_and_pause);
imgPlayAndPause.setOnClickListener(this);
imgDownloaded = findViewById(R.id.img_downloaded);
imgOption = findViewById(R.id.img_option);
imgOption.setOnClickListener(this);
imgDownloaded.setOnClickListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction(DownloadedActivity.UPDATE_MUSIC);
tvDownloadIntent = findViewById(R.id.tv_download_intent);
tvDownloadIntent.setOnClickListener(this);
lvHotSongs = findViewById(R.id.lv_hot_songs);
LinearLayoutManager layoutManagerHotSongs = new LinearLayoutManager(this);
layoutManagerHotSongs.setOrientation(LinearLayoutManager.VERTICAL);
lvHotSongs.setLayoutManager(layoutManagerHotSongs);
adapterMusicSearch = new AdapterMusicSearch(arrHotSongs, this);
adapterMusicSearch.setCallBack(this);
lvHotSongs.setAdapter(adapterMusicSearch);
loadHotSongs();
}
public void onClickTag(View view) {
TextView textView = (TextView) view;
Intent intent = new Intent(this, DownloadActivity.class);
intent.putExtra("KEY_TAG", textView.getText());
startActivity(intent);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_search_song:
startActivity(new Intent(this, DownloadActivity.class));
break;
case R.id.img_downloaded:
startActivity(new Intent(this, DownloadedActivity.class));
break;
case R.id.img_option:
PopupMenu popupMenu = new PopupMenu(this, imgOption);
popupMenu.inflate(R.menu.menu_option);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
shareApp();
return true;
case R.id.menu_rate:
rateApp();
return true;
default:
return false;
}
}
});
popupMenu.show();
break;
default:
break;
}
}
private void rateApp() {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
}
private void shareApp() {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage = "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID + "\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch (Exception e) {
Toast.makeText(this, "share app error", Toast.LENGTH_SHORT).show();
}
}
private void showDialogRating() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_rating_app);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
Button btnCancel = dialog.findViewById(R.id.btn_cancel_rating);
Button btnOkRating = dialog.findViewById(R.id.btn_ok_rating);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btnOkRating.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkFirst.edit().putString(CHECK_FIRST, "2").commit();
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
dialog.dismiss();
}
});
}
public void loadHotSongs() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.googleapis.com/youtube/v3/").addConverterFactory(GsonConverterFactory.create()).build();
JsonGetDataByRetrofit jsonGetData = retrofit.create(JsonGetDataByRetrofit.class);
try {
Call<Example> call = jsonGetData.getHotSongs(randomKey());
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Call<Example> call, Response<Example> response) {
try {
if (response.body().getItems() != null) {
for (int i = 0; i < response.body().getItems().size(); i++) {
String category = response.body().getItems().get(i).getSnippet().getCategoryId();
if (category.equals("10")) {
String id = response.body().getItems().get(i).getId();
String title = response.body().getItems().get(i).getSnippet().getTitle();
String auth = response.body().getItems().get(i).getSnippet().getChannelTitle();
String linkImage = "";
linkImage = response.body().getItems().get(i).getSnippet().getThumbnails().getMedium().getUrl();
if (!id.contains("-")) {
arrHotSongs.add(new Song(id, title, auth, linkImage));
}
adapterMusicSearch.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
Log.e("error", "error get hot songs");
}
}
@Override
public void onFailure
(Call<Example> call, Throwable
t) {
Toast.makeText(MainActivity.this
, "Error", Toast.LENGTH_SHORT).show();
}
});
call.clone();
} catch (
Exception ex) {
Toast.makeText(MainActivity.this, "please wait", Toast.LENGTH_SHORT).show();
}
}
@Override
public void clickItem(int position) {
Intent intent = new Intent(this, DownloadActivity.class);
intent.putExtra(HOT_SONGS_ID, arrHotSongs.get(position).getIdMusic());
intent.putExtra(HOT_SONGS_TITLE, arrHotSongs.get(position).getTitle());
startActivity(intent);
}
@Override
public void clickItemDownload(int position) {
}
解决方案
您首先需要res/menu/my_navigation_items.xml
在底部导航栏中为您的项目定义一个
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
android:title="@string/menu_search"
android:icon="@drawable/ic_search" />
<item android:id="@+id/action_settings"
android:title="@string/menu_settings"
android:icon="@drawable/ic_add" />
<item android:id="@+id/action_navigation"
android:title="@string/menu_navigation"
android:icon="@drawable/ic_action_navigation_menu" />
</menu>
然后你BottomNavigationView
在你的xml中添加一个作为app:menu
你之前创建的菜单
<com.google.android.material.bottomnavigation.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schema.android.com/apk/res/res-auto"
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_gravity="start"
app:menu="@menu/my_navigation_items" />
然后在您应该使用的项目之间导航BottomNavigationView.OnNavigationItemSelectedListener
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id. action_search:
//showYourFragmentForActionSearch
case R.id. action_settings:
//showYourFragmentForActionSettings
case R.id. action_navigation:
//showYourFragmentForActionNavigation
}
return false;
}
};
然后将其设置BottomNavigationView.OnNavigationItemSelectedListener
为您BottomNavigationView
之前在布局中创建的
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
有了这个,如果您想了解更多详细信息,您可以了解如何使用,BottomNavigationView
请随时查看此BottomNavViewsWithFragments
存储库。
推荐阅读
- drop-down-menu - 如何使用 ag 网格根据两个下拉选择显示和隐藏列
- python-3.x - findEssentialMat(openCV)中“焦距= 1.0”的单位是什么?
- javascript - 在 Javascript 中使用 for 循环交换字符串的大小写
- python - 如何确保 BeautifulSoup 不会将逗号视为制表符
- javascript - 如何将 UI 更新推送到 javascript 前端?
- java - 多次收到 API 响应
- excel - 确定具有字母数字值的列中的最大大小和最小大小
- reactjs - 为什么在反应中删除后组件不重新渲染
- python - Sklearn 错误无法将大小为 6912 的数组重塑为形状 (614,154)
- jquery - 谷歌地理编码自动完成限制在马里兰州