AlertDialog、PopupWindow 与 Activity 之间区别

1、使用 AlertDialog 和 PopupWindow 实现对话

1.1 使用 PopupWindow 实现自定义对话框

PopupWindow 就是一个悬浮在 Activity 之上的窗口,可以用展示任意布局文件。PopupWindow 是在 Android 上实现自定义对话框的众多方式之一。下面是它用来实现对话框的一个示例:

我们想要实现的效果如下所示:
UI效果

如果我们使用Android的PopDialog的话实现这种效果会比较繁琐,我们可以通过自定义对话框解决这个问题:

public class PopDialogController {
   

    public static void showSortDialog(Activity activity, View view, OnMenuItemSelectedListener onMenuItemSelectedListener) {
   
        // 这里我们使用PopupWindow来达到上述效果
        PopupWindow popDialog = new PopupWindow();

        // 一个枚举,用来指定默认的选项
        SortField sortField = SortField.fromValue(PersistData.getInteger(Constants.KEY_SORT_FIELD, SortField.CreateDate.value));

        // 加载布局文件
        View root = LayoutInflater.from(activity).inflate(R.layout.dialog_pop_sort, null, false);
        // 设置按钮的单击事件并进行回调
        root.findViewById(R.id.ll_receipt_date).setOnClickListener(v 
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
AlertDialog通常使用setPositiveButton()和setNegativeButton()方法来设置对话框的按钮。这些按钮默认是在对话框底部排列,且宽度相等。 如果你想要自定义按钮的位置和宽度,可以使用setView()方法来自定义AlertDialog的布局。你可以创建一个布局文件,然后在其中添加两个按钮,并设置它们的位置和宽度。然后在AlertDialog中使用setView()方法将该布局文件设置为对话框的视图。 以下是一个示例布局文件,其中包含两个按钮,一个在左侧,一个在右侧,并且它们的宽度不同: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/left_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="Left" /> <Button android:id="@+id/right_button" android:layout_width="0dp" android:layout_weight="2" android:layout_height="wrap_content" android:text="Right" /> </LinearLayout> ``` 然后在代码中,你可以使用以下方法来设置AlertDialog的视图,并将其中的按钮设置为自定义布局中的按钮: ``` AlertDialog.Builder builder = new AlertDialog.Builder(context); View customLayout = LayoutInflater.from(context).inflate(R.layout.custom_layout, null); builder.setView(customLayout); Button leftButton = customLayout.findViewById(R.id.left_button); Button rightButton = customLayout.findViewById(R.id.right_button); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Do something when left button is clicked } }); rightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Do something when right button is clicked } }); AlertDialog dialog = builder.create(); dialog.show(); ``` 这样,你就可以自定义AlertDialog的按钮位置和宽度了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值