欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android自定义view仿iOS弹出框效果

程序员文章站 2022-10-13 09:40:36
本文实例为大家分享了android自定义view仿ios弹出框的具体代码,供大家参考,具体内容如下 运行效果图 自定义对话框的使用,仿照ios。从底部弹出,类似po...

本文实例为大家分享了android自定义view仿ios弹出框的具体代码,供大家参考,具体内容如下

运行效果图

Android自定义view仿iOS弹出框效果

自定义对话框的使用,仿照ios。从底部弹出,类似pop窗口。包括消息、图片、列表及对话框。

好了,用法都会,直接贴上代码

1.layout布局文件

view_actionsheet.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  android:padding="8dp">

  <textview
    android:id="@+id/txt_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/actionsheet_top_normal"
    android:gravity="center"
    android:minheight="45dp"
    android:paddingbottom="10dp"
    android:paddingleft="15dp"
    android:paddingright="15dp"
    android:paddingtop="10dp"
    android:textcolor="@color/actionsheet_gray"
    android:textsize="13sp"
    android:visibility="gone" />

  <scrollview
    android:id="@+id/slayout_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fadingedge="none">

    <linearlayout
      android:id="@+id/llayout_content"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"></linearlayout>
  </scrollview>

  <textview
    android:id="@+id/txt_cancel"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:layout_margintop="8dp"
    android:background="@drawable/actionsheet_single_selector"
    android:gravity="center"
    android:text="取消"
    android:textcolor="@color/actionsheet_blue"
    android:textsize="18sp" />

</linearlayout>

view_alertdialog.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/llayout_bg"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/alert_bg"
  android:orientation="vertical">

  <textview
    android:id="@+id/txt_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginleft="15dp"
    android:layout_marginright="15dp"
    android:layout_margintop="15dp"
    android:gravity="center"
    android:textcolor="@color/black"
    android:textsize="18sp"
    android:textstyle="bold" />

  <textview
    android:id="@+id/txt_msg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginleft="15dp"
    android:layout_marginright="15dp"
    android:layout_margintop="15dp"
    android:gravity="center"
    android:textcolor="@color/black"
    android:textsize="16sp" />

  <imageview
    android:layout_width="match_parent"
    android:layout_height="0.5dp"
    android:layout_margintop="10dp"
    android:background="@color/alertdialog_line" />

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <button
      android:id="@+id/btn_neg"
      android:layout_width="wrap_content"
      android:layout_height="43dp"
      android:layout_weight="1"
      android:background="@drawable/alertdialog_left_selector"
      android:gravity="center"
      android:textcolor="@color/actionsheet_blue"
      android:textsize="16sp" />

    <imageview
      android:id="@+id/img_line"
      android:layout_width="0.5dp"
      android:layout_height="43dp"
      android:background="@color/alertdialog_line" />

    <button
      android:id="@+id/btn_pos"
      android:layout_width="wrap_content"
      android:layout_height="43dp"
      android:layout_weight="1"
      android:background="@drawable/alertdialog_right_selector"
      android:gravity="center"
      android:textcolor="@color/actionsheet_blue"
      android:textsize="16sp" />
  </linearlayout>

</linearlayout>

2.style.xml文件

<style name="actionsheetdialogstyle" parent="android:theme.dialog">

    <!-- 背景透明 -->
    <item name="android:windowbackground">@android:color/transparent</item>
    <item name="android:windowcontentoverlay">@null</item>
    <!-- 浮于activity之上 -->
    <item name="android:windowisfloating">true</item>
    <!-- 边框 -->
    <item name="android:windowframe">@null</item>
    <!-- dialog以外的区域模糊效果 -->
    <item name="android:backgrounddimenabled">true</item>
    <!-- 无标题 -->
    <item name="android:windownotitle">true</item>
    <!-- 半透明 -->
    <item name="android:windowistranslucent">true</item>
    <!-- dialog进入及退出动画 -->
    <item name="android:windowanimationstyle">@style/actionsheetdialoganimation</item>
  </style>
  <!-- actionsheet进出动画 -->
  <style name="actionsheetdialoganimation" parent="@android:style/animation.dialog">
    <item name="android:windowenteranimation">@anim/actionsheet_dialog_in</item>
    <item name="android:windowexitanimation">@anim/actionsheet_dialog_out</item>
  </style>
  <!-- 头部字体样式 -->
  <style name="etitle" parent="@android:style/widget.button">
    <item name="android:textcolor">@color/actionsheet_blue</item>
    <item name="android:textsize">@dimen/nav_title_text_size</item>
  </style>

  <style name="alertdialogstyle" parent="@android:style/theme.dialog">
    <item name="android:windowbackground">@android:color/transparent</item>
    <item name="android:windowcontentoverlay">@null</item>
    <item name="android:windowisfloating">true</item>
    <item name="android:windowframe">@null</item>
    <item name="android:backgrounddimenabled">true</item>
    <item name="android:windownotitle">true</item>
    <item name="android:windowistranslucent">true</item>
  </style>

3.color.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="colorprimary">#3f51b5</color>
  <color name="colorprimarydark">#303f9f</color>
  <color name="coloraccent">#ff4081</color>


  <color name="black">#000000</color>
  <color name="trans">#00000000</color>
  <color name="alertdialog_line">#c6c6c6</color>
  <color name="actionsheet_blue">#037bff</color>
  <color name="actionsheet_red">#fd4a2e</color>
  <color name="actionsheet_gray">#8f8f8f</color>
</resources>

4.dimen.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <!-- default screen margins, per the android design guidelines. -->
  <dimen name="activity_horizontal_margin">16dp</dimen>
  <dimen name="activity_vertical_margin">16dp</dimen>
  <dimen name="nav_title_text_size">20sp</dimen>
</resources>

5.anim动画

actionsheet_dialog_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
  android:duration="200"
  android:fromydelta="100%"
  android:toydelta="0" />

actionsheet_dialog_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
  android:duration="200"
  android:fromydelta="0"
  android:toydelta="100%" />

6.drawable文件夹的诸多资源

资源下载来源

7.底部弹出框

import android.app.dialog;
import android.content.context;
import android.graphics.color;
import android.view.display;
import android.view.gravity;
import android.view.layoutinflater;
import android.view.view;
import android.view.viewgroup;
import android.view.window;
import android.view.windowmanager;
import android.widget.linearlayout;
import android.widget.scrollview;
import android.widget.textview;
import java.util.arraylist;
import java.util.list;

/**
 * author:and
 * time:2018/3/16.
 * email:2911743255@qq.com
 * description:
 * detail:
 */

public class actionsheetdialog {
  private context context;
  private dialog dialog;
  private textview txt_title;
  private textview txt_cancel;
  private linearlayout llayout_content;
  private scrollview slayout_content;
  private boolean showtitle = false;
  private list<sheetitem> sheetitemlist;
  private display display;

  public actionsheetdialog(context context) {
    this.context = context;
    windowmanager windowmanager = (windowmanager) context
        .getsystemservice(context.window_service);
    display = windowmanager.getdefaultdisplay();
  }

  public actionsheetdialog builder() {
    // 获取dialog布局
    view view = layoutinflater.from(context).inflate(
        r.layout.view_actionsheet, null);

    // 设置dialog最小宽度为屏幕宽度
    view.setminimumwidth(display.getwidth());

    // 获取自定义dialog布局中的控件
    slayout_content = (scrollview) view.findviewbyid(r.id.slayout_content);
    llayout_content = (linearlayout) view
        .findviewbyid(r.id.llayout_content);
    txt_title = (textview) view.findviewbyid(r.id.txt_title);
    txt_cancel = (textview) view.findviewbyid(r.id.txt_cancel);
    txt_cancel.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        dialog.dismiss();
      }
    });

    // 定义dialog布局和参数
    dialog = new dialog(context, r.style.actionsheetdialogstyle);
    dialog.setcontentview(view);
    window dialogwindow = dialog.getwindow();
    dialogwindow.setgravity(gravity.left | gravity.bottom);
    windowmanager.layoutparams lp = dialogwindow.getattributes();
    lp.x = 0;
    lp.y = 0;
    dialogwindow.setattributes(lp);

    return this;
  }

  public actionsheetdialog settitle(string title) {
    showtitle = true;
    txt_title.setvisibility(view.visible);
    txt_title.settext(title);
    return this;
  }

  public actionsheetdialog setcancelable(boolean cancel) {
    dialog.setcancelable(cancel);
    return this;
  }

  public actionsheetdialog setcanceledontouchoutside(boolean cancel) {
    dialog.setcanceledontouchoutside(cancel);
    return this;
  }

  /**
   * @param stritem 条目名称
   * @param color  条目字体颜色,设置null则默认蓝色
   * @param listener
   * @return
   */
  public actionsheetdialog addsheetitem(string stritem, sheetitemcolor color,
                     onsheetitemclicklistener listener) {
    if (sheetitemlist == null) {
      sheetitemlist = new arraylist<sheetitem>();
    }
    sheetitemlist.add(new sheetitem(stritem, color, listener));
    return this;
  }

  /**
   * 设置条目布局
   */
  private void setsheetitems() {
    if (sheetitemlist == null || sheetitemlist.size() <= 0) {
      return;
    }

    int size = sheetitemlist.size();

    // todo 高度控制,非最佳解决办法
    // 添加条目过多的时候控制高度
    if (size >= 7) {
      viewgroup.layoutparams params = (viewgroup.layoutparams) slayout_content
          .getlayoutparams();
      params.height = display.getheight() / 2;
      slayout_content.setlayoutparams(params);
    }

    // 循环添加条目
    for (int i = 1; i <= size; i++) {
      final int index = i;
      sheetitem sheetitem = sheetitemlist.get(i - 1);
      string stritem = sheetitem.name;
      sheetitemcolor color = sheetitem.color;
      final onsheetitemclicklistener listener = (onsheetitemclicklistener) sheetitem.itemclicklistener;

      textview textview = new textview(context);
      textview.settext(stritem);
      textview.settextsize(18);
      textview.setgravity(gravity.center);

      // 背景图片
      if (size == 1) {
        if (showtitle) {
          textview.setbackgroundresource(r.drawable.actionsheet_bottom_selector);
        } else {
          textview.setbackgroundresource(r.drawable.actionsheet_single_selector);
        }
      } else {
        if (showtitle) {
          if (i >= 1 && i < size) {
            textview.setbackgroundresource(r.drawable.actionsheet_middle_selector);
          } else {
            textview.setbackgroundresource(r.drawable.actionsheet_bottom_selector);
          }
        } else {
          if (i == 1) {
            textview.setbackgroundresource(r.drawable.actionsheet_top_selector);
          } else if (i < size) {
            textview.setbackgroundresource(r.drawable.actionsheet_middle_selector);
          } else {
            textview.setbackgroundresource(r.drawable.actionsheet_bottom_selector);
          }
        }
      }

      // 字体颜色
      if (color == null) {
        textview.settextcolor(color.parsecolor(sheetitemcolor.blue
            .getname()));
      } else {
        textview.settextcolor(color.parsecolor(color.getname()));
      }

      // 高度
      float scale = context.getresources().getdisplaymetrics().density;
      int height = (int) (45 * scale + 0.5f);
      textview.setlayoutparams(new viewgroup.layoutparams(
          viewgroup.layoutparams.match_parent, height));

      // 点击事件
      textview.setonclicklistener(new view.onclicklistener() {
        @override
        public void onclick(view v) {
          listener.onclick(index);
          dialog.dismiss();
        }
      });

      llayout_content.addview(textview);
    }
  }

  public void show() {
    setsheetitems();
    dialog.show();
  }

  public interface onsheetitemclicklistener {
    void onclick(int which);
  }

  public class sheetitem {
    string name;
    onsheetitemclicklistener itemclicklistener;
    sheetitemcolor color;

    public sheetitem(string name, sheetitemcolor color,
             onsheetitemclicklistener itemclicklistener) {
      this.name = name;
      this.color = color;
      this.itemclicklistener = itemclicklistener;
    }
  }

  public enum sheetitemcolor {
    blue("#037bff"), red("#fd4a2e");

    private string name;

    private sheetitemcolor(string name) {
      this.name = name;
    }

    public string getname() {
      return name;
    }

    public void setname(string name) {
      this.name = name;
    }
  }
}

8.中间弹出框

import android.app.dialog;
import android.content.context;
import android.view.display;
import android.view.layoutinflater;
import android.view.view;
import android.view.viewgroup;
import android.view.windowmanager;
import android.widget.button;
import android.widget.framelayout;
import android.widget.imageview;
import android.widget.linearlayout;
import android.widget.textview;

/**
 * author:and
 * time:2018/3/16.
 * email:2911743255@qq.com
 * description:
 * detail:
 */

public class alertdialog {
  private context context;
  private dialog dialog;
  private linearlayout llayout_bg;
  private textview txt_title;
  private textview txt_msg;
  private button btn_neg;
  private button btn_pos;
  private imageview img_line;
  private display display;
  private boolean showtitle = false;
  private boolean showmsg = false;
  private boolean showposbtn = false;
  private boolean shownegbtn = false;

  public alertdialog(context context) {
    this.context = context;
    windowmanager windowmanager = (windowmanager) context
        .getsystemservice(context.window_service);
    display = windowmanager.getdefaultdisplay();
  }

  public alertdialog builder() {
    // 获取dialog布局
    view view = layoutinflater.from(context).inflate(
        r.layout.view_alertdialog, null);

    // 获取自定义dialog布局中的控件
    llayout_bg = (linearlayout) view.findviewbyid(r.id.llayout_bg);
    txt_title = (textview) view.findviewbyid(r.id.txt_title);
    txt_title.setvisibility(view.gone);
    txt_msg = (textview) view.findviewbyid(r.id.txt_msg);
    txt_msg.setvisibility(view.gone);
    btn_neg = (button) view.findviewbyid(r.id.btn_neg);
    btn_neg.setvisibility(view.gone);
    btn_pos = (button) view.findviewbyid(r.id.btn_pos);
    btn_pos.setvisibility(view.gone);
    img_line = (imageview) view.findviewbyid(r.id.img_line);
    img_line.setvisibility(view.gone);

    // 定义dialog布局和参数
    dialog = new dialog(context, r.style.alertdialogstyle);
    dialog.setcontentview(view);

    // 调整dialog背景大小
    llayout_bg.setlayoutparams(new framelayout.layoutparams((int) (display
        .getwidth() * 0.85), viewgroup.layoutparams.wrap_content));

    return this;
  }

  public alertdialog settitle(string title) {
    showtitle = true;
    if ("".equals(title)) {
      txt_title.settext("标题");
    } else {
      txt_title.settext(title);
    }
    return this;
  }

  public alertdialog setmsg(string msg) {
    showmsg = true;
    if ("".equals(msg)) {
      txt_msg.settext("内容");
    } else {
      txt_msg.settext(msg);
    }
    return this;
  }

  public alertdialog setcancelable(boolean cancel) {
    dialog.setcancelable(cancel);
    return this;
  }

  public alertdialog setpositivebutton(string text,
                     final view.onclicklistener listener) {
    showposbtn = true;
    if ("".equals(text)) {
      btn_pos.settext("确定");
    } else {
      btn_pos.settext(text);
    }
    btn_pos.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        listener.onclick(v);
        dialog.dismiss();
      }
    });
    return this;
  }

  public alertdialog setnegativebutton(string text,
                     final view.onclicklistener listener) {
    shownegbtn = true;
    if ("".equals(text)) {
      btn_neg.settext("取消");
    } else {
      btn_neg.settext(text);
    }
    btn_neg.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        listener.onclick(v);
        dialog.dismiss();
      }
    });
    return this;
  }

  private void setlayout() {
    if (!showtitle && !showmsg) {
      txt_title.settext("提示");
      txt_title.setvisibility(view.visible);
    }

    if (showtitle) {
      txt_title.setvisibility(view.visible);
    }

    if (showmsg) {
      txt_msg.setvisibility(view.visible);
    }

    if (!showposbtn && !shownegbtn) {
      btn_pos.settext("确定");
      btn_pos.setvisibility(view.visible);
      btn_pos.setbackgroundresource(r.drawable.alertdialog_single_selector);
      btn_pos.setonclicklistener(new view.onclicklistener() {
        @override
        public void onclick(view v) {
          dialog.dismiss();
        }
      });
    }

    if (showposbtn && shownegbtn) {
      btn_pos.setvisibility(view.visible);
      btn_pos.setbackgroundresource(r.drawable.alertdialog_right_selector);
      btn_neg.setvisibility(view.visible);
      btn_neg.setbackgroundresource(r.drawable.alertdialog_left_selector);
      img_line.setvisibility(view.visible);
    }

    if (showposbtn && !shownegbtn) {
      btn_pos.setvisibility(view.visible);
      btn_pos.setbackgroundresource(r.drawable.alertdialog_single_selector);
    }

    if (!showposbtn && shownegbtn) {
      btn_neg.setvisibility(view.visible);
      btn_neg.setbackgroundresource(r.drawable.alertdialog_single_selector);
    }
  }

  public void show() {
    setlayout();
    dialog.show();
  }
}

9.具体使用

activity调用

@override
  public void onclick(view v) {
    switch (v.getid()) {
      case r.id.click:
        // todo 18/03/16
        new actionsheetdialog(this)
            .builder()
            .settitle("清空消息列表后,聊天记录依然保留,确定要清空消息列表?")
            .setcancelable(false)
            .setcanceledontouchoutside(false)
            .addsheetitem("清空消息列表", actionsheetdialog.sheetitemcolor.red
                , new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                }).show();
        break;
      case r.id.iamge:// todo 18/03/16
        new actionsheetdialog(this)
            .builder()
            .setcancelable(false)
            .setcanceledontouchoutside(false)
            .addsheetitem("发送给好友", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                })
            .addsheetitem("转载到空间相册", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                })
            .addsheetitem("上传到群相册", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                })
            .addsheetitem("保存到手机", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                })
            .addsheetitem("收藏", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                })
            .addsheetitem("查看聊天图片", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                }).show();
        break;
      case r.id.ctrol:// todo 18/03/16
        new actionsheetdialog(this)
            .builder()
            .settitle("请选择操作")
            .setcancelable(false)
            .setcanceledontouchoutside(false)
            .addsheetitem("条目一", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {

                  }
                })
            .addsheetitem("条目二", actionsheetdialog.sheetitemcolor.blue,
                new actionsheetdialog.onsheetitemclicklistener() {
                  @override
                  public void onclick(int which) {
                  }
                }).show();
        break;

      case r.id.login:// todo 18/03/16
        new alertdialog(this).builder().settitle("退出当前账号")
            .setmsg("再连续登陆15天,就可变身为qq达人。退出qq可能会使你现有记录归零,确定退出?")
            .setpositivebutton("确认退出", new view.onclicklistener() {
              @override
              public void onclick(view v) {

              }
            }).setnegativebutton("取消", new view.onclicklistener() {
          @override
          public void onclick(view v) {

          }
        }).show();
        break;

      case r.id.msg:// todo 18/03/16
        new alertdialog(this).builder()
            .setmsg("你现在无法接收到新消息提醒。请到系统-设置-通知中开启消息提醒")
            .setnegativebutton("确定", new view.onclicklistener() {
              @override
              public void onclick(view v) {

              }
            }).show();

        break;
      default:
        break;
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。