Android studio使用Snackbar点击按钮带图标方式显示消息提示
时间: 2023-12-14 13:28:24 浏览: 51
要在Android Studio中使用Snackbar点击按钮带图标方式显示消息提示,需要遵循以下步骤:
1.在app/build.gradle文件中添加以下依赖项:
```
implementation 'com.android.support:design:28.0.0'
```
这将添加支持Snackbar的Material Design库。
2.在布局文件中添加一个Button和一个Snackbar容器View:
```
<RelativeLayout
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Snackbar"/>
<LinearLayout
android:id="@+id/snackbar_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
```
3.在Activity中获取Button和Snackbar容器View的引用:
```
Button myButton = findViewById(R.id.my_button);
View snackbarContainer = findViewById(R.id.snackbar_container);
```
4.在Button的onClick事件中,创建Snackbar实例并设置消息内容和图标:
```
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar snackbar = Snackbar.make(snackbarContainer, "This is a Snackbar message", Snackbar.LENGTH_LONG);
//设置Snackbar中的图标
Drawable icon = getResources().getDrawable(R.drawable.ic_info_outline);
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
TextView textView = snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
textView.setCompoundDrawables(icon, null, null, null);
textView.setCompoundDrawablePadding(getResources().getDimensionPixelOffset(R.dimen.snackbar_icon_padding));
snackbar.show();
}
});
```
这将创建一个Snackbar实例,将其附加到Snackbar容器View中,并在Snackbar消息中添加一个带有指定图标的TextView。
现在,当用户点击按钮时,Snackbar将显示在屏幕底部,并显示指定的消息和图标。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)