Xamarin Forms Wear OS Android自定义ActionSheet顶部留白去除咨询
解决Wear手表Xamarin Forms Android自定义ActionSheet顶部留白问题
问题背景
在Wear手表的Xamarin Forms Android应用中,因默认ActionSheet为白色不符合应用商店要求,自定义了黑色样式的ActionSheet,但实际运行时界面顶部出现留白,需要去除该留白。
解决步骤
1. 移除AlertDialog默认标题预留区域
AlertDialog.Builder默认会为标题保留空白区域,即使未设置标题也会存在留白。在CreateDialog方法中添加SetCustomTitle(null)清除该预留:
private void CreateDialog(String title, String message, params String[] buttons) { AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.PrimaryActivity); // 移除默认标题区域的留白 adb.SetCustomTitle(null); LayoutInflater inflater = Android.Views.LayoutInflater.FromContext(MainActivity.PrimaryActivity); Android.Views.View v = inflater.Inflate(Resource.Layout.CustomActionSheet, null); v.SetBackgroundColor(Android.Graphics.Color.Black); // 其余原有代码保持不变 }
2. 调整自定义布局的根容器宽度
修改CustomActionSheet.axml的根LinearLayout宽度为match_parent,确保布局填满对话框空间,避免因宽度适配产生的留白:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/background_dark"> <!-- 其余原有控件代码保持不变 --> </LinearLayout>
3. 清除对话框Window的额外内边距
在对话框显示后,获取其Window对象,设置黑色背景并清除内边距,彻底消除顶部留白:
public Task<String> UseActionSheet(Page p, String title, String message, params String[] buttons) { // 其余原有代码保持不变 try { Activity act = MainActivity.PrimaryActivity; if (act != null) { CreateDialog(title, message, buttons); if (dlg != null) { dlg.Show(); // 清除Window内边距并设置黑色背景 dlg.Window.SetBackgroundDrawable(new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.Black)); dlg.Window.DecorView.SetPadding(0, 0, 0, 0); } } } catch (Exception e) { p.DisplayAlert("Error", e.Message, "OK"); } return tcs.Task; }
额外检查项
- 若
messageTextView的android:layout_margin="20dp"是顶部留白的来源之一,可单独调整为android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="10dp"(根据视觉需求调整数值) - 检查
TextViewItem布局是否存在额外内边距,避免列表项带来的留白
内容的提问来源于stack exchange,提问作者Kees Dapperens
相关产品推荐
相关产品推荐

