xamarin android alertdialog详解

小编 2026-07-02 阅读:898 评论:0
说明一下:学习xamarin android一段时间,准备写一些xamarin android相...

说明一下:学习xamarin android一段时间,准备写一些xamarin android相关的例子,alertdialog也是使用的非常多得空间之一,非常感谢鸟巢上的小猪,我也是看着他写的教程学会的。参考他的那一章 http://www.runoob.com/w3cnote/android-tutorial-alertdialog.html

1.基本使用流程

  • Step 1:创建AlertDialog.Builder对象;
  • Step 2:调用setIcon()设置图标,setTitle()setCustomTitle()设置标题;
  • Step 3:设置对话框的内容:setMessage()还有其他方法来指定显示的内容;
  • Step 4:调用setPositive/Negative/NeutralButton()设置:确定,取消,中立按钮;
  • Step 5:调用create()方法创建这个对象,再调用show()方法将对话框显示出来;

2.几种常用的对话框使用示例

运行效果图:

 xamarin android alertdialog详解

主要代码:MainActivity.class

public class MainActivity : Activity    {        int count = 1;        private Button btn_alertDialog_one, btn_alertDialog_two, btn_alertDialog_three, btn_alertDialog_four;        private bool[] checkItems;        private AlertDialog alertDialog = null;        private AlertDialog.Builder builder = null;        protected override void OnCreate(Bundle bundle)        {            base.OnCreate(bundle);            SetContentView(Resource.Layout.Main);             bindViewClick();        }        private void bindViewClick()        {            btn_alertDialog_four = FindViewById<Button>(Resource.Id.btn_alertDialog_four);            btn_alertDialog_three = FindViewById<Button>(Resource.Id.btn_alertDialog_three);            btn_alertDialog_two = FindViewById<Button>(Resource.Id.btn_alertDialog_two);            btn_alertDialog_one = FindViewById<Button>(Resource.Id.btn_alertDialog_one);            btn_alertDialog_one.Click += delegate { onClick(btn_alertDialog_one); };            btn_alertDialog_two.Click += delegate { onClick(btn_alertDialog_two); };            btn_alertDialog_three.Click += delegate { onClick(btn_alertDialog_three); };            btn_alertDialog_four.Click += delegate { onClick(btn_alertDialog_four); };        }        private void onClick(View v)        {            switch (v.Id)            {                case Resource.Id.btn_alertDialog_one:                    alertDialog = null;                    builder = new AlertDialog.Builder(this);                    alertDialog = builder                   .SetTitle("sure")                   .SetMessage("are you sure exit?")                   .SetNegativeButton("cancel", (s, e) =>                    {                        Toast.MakeText(this, "you click cancel", ToastLength.Short).Show();                    })                   .SetPositiveButton("sure", (s, e) =>                   {                       Toast.MakeText(this, "you click sure", ToastLength.Short).Show();                   })                   .SetNeutralButton("neutra", (s, e) => {                       Toast.MakeText(this, "you click neutra", ToastLength.Short).Show();                   })                   .Create();       //创建alertDialog对象                               alertDialog.Show();                    var dialog = new AlertDialog.Builder(this);                    break;                case Resource.Id.btn_alertDialog_two:                    alertDialog = null;                    builder = new AlertDialog.Builder(this);                    string[] players = new string[] {"杜兰特","汤普森","考辛斯","卡戴珊"};                    alertDialog = builder                        .SetIcon(Resource.Drawable.players)                        .SetTitle("选择你喜欢的球员")                         .SetItems(players, (s, e) =>                         {                             Toast.MakeText(this, "you selected " + players[e.Which], ToastLength.Short).Show();                         })                        .Create();                    alertDialog.Show();                    break;                case Resource.Id.btn_alertDialog_three:                    var a = new AlertDialog.Builder(this);                    string[] teams = new string[] {"骑士","公牛","快船","马刺","勇士" };                    a.SetTitle("你认为下个赛季哪只球队能夺冠")                        .SetSingleChoiceItems(teams, 0, (s, e) =>                        {                            Toast.MakeText(this, "you selected " + teams[e.Which], ToastLength.Short).Show();                        })                        .Create();                    a.Show();                    break;                 case Resource.Id.btn_alertDialog_four:                    var b = new AlertDialog.Builder(this);                    string[] menu = new string[] { "麻婆豆腐","羊蝎子","驴肉火烧","辣子鸡丁"};                    checkItems = new bool[] {false,false,false,false};                    b = b.SetIcon(Resource.Drawable.Icon)                      .SetMultiChoiceItems(menu, checkItems, (s, e) => {                            //Toast.MakeText(this, "you selected " + menu[e.Which], ToastLength.Short).Show();                            checkItems[e.Which] = e.IsChecked;                      })                      .SetPositiveButton("确定", (s, e) => {                          string result = string.Empty;                          for (int i = 0; i < checkItems.Length; i++)                          {                              if (checkItems[i])                              {                                  result += menu[i] + ",";                              }                          }                          Toast.MakeText(this, "you selected " + result, ToastLength.Short).Show();                      });                    b.Create();                    b.Show();                    break;            }        }    }

用法非常简单创建一个Builder对象后,调用Create方法创建一个AlertDialog对象,最后调用show方法显示出来,当然你也可以像这样直接new 一个AlertDialog对象

 var b = new AlertDialog.Builder(this);
 设置一个setCancelable (true|false)看看有没有什么区别

3.通过Builder的setView()定制显示的AlertDialog

我们可以自定义一个与系统对话框不同的布局,然后调用setView()将我们的布局加载到AlertDialog上,上面我们来实现这个效果:

xamarin android alertdialog详解

我就贴一下几个主要的布局和样式文件

1.对话框头部的取消按钮样式:在drawable文件下创建一个btn_selector_exit.xml文件,在这里要注意一点item下的属性android:background=“#dedede”,这样直接写会报错,我这里用的是换颜色,所以我在string.xml文件下写了两个颜色,大家要注意一下,我有点想不通的是为什么background属性直接写颜色代码会出错,有点郁闷,如果你有好的解释也可以告诉我这个android的 菜鸟

  <drawable name="pressed_color">#0cb026</drawable>
  <drawable name="default_color">#53cc66</drawable>

<?xml version="1.0" encoding="utf-8" ?><selector xmlns:android="http://schemas.android.com/apk/res/android">  <item android:state_pressed="true" android:drawable="@drawable/exit_press"/>  <item android:drawable="@drawable/exit"/></selector>

2.底部两个按钮按下换背景色的样式新建一个btn_selector_choose.xml文件

<?xml version="1.0" encoding="utf-8" ?><selector xmlns:android="http://schemas.android.com/apk/res/android">  <item android:state_pressed="true"  android:drawable="@drawable/pressed_color"  />  <item  android:drawable="@drawable/default_color"  /></selector>

3.最重要的还是<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/layout_relative"    android:layout_width="match_parent"    android:layout_height="match_parent"><!--头部-->    <RelativeLayout        android:id="@+id/layout_title"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:background="#53cc66"        android:padding="5dp">        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_centerVertical="true"            android:text="提示文本"            android:textSize="18sp"            android:textStyle="bold"           android:textColor="#ffffff"        />        <Button            android:id="@+id/btn_cancel"            android:layout_width="30dp"            android:layout_height="30dp"            android:layout_alignParentRight="true"            android:background="@drawable/btn_selector_exit" />    </RelativeLayout><!--中间内容-->    <LinearLayout        android:id="@+id/layout_detail"        android:layout_height="wrap_content"        android:layout_width="match_parent"        android:layout_below="@+id/layout_title"        android:layout_centerInParent="true"        android:orientation="vertical"       android:background="#f1f1f1"        android:padding="20dp"        >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="通过setView方法定制alertDialog"            android:textColor="#04AEDA"            android:textSize="18sp" />            <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="作者:张林"            android:textColor="#04AEDA"            android:textSize="18sp" />    </LinearLayout><!--底部按钮-->    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/layout_detail"        android:orientation="horizontal"        android:background="#f1f1f1"        android:padding="5dp"      >        <Button            android:id="@+id/btn_blog"            android:layout_width="match_parent"            android:layout_height="40dp"            android:layout_weight="1"            android:background="@drawable/btn_selector_choose"            android:text="访问博客"            android:textColor="#ffffff"            android:textSize="20sp"            android:layout_marginRight="5dp"      />               <Button            android:id="@+id/btn_close"            android:layout_width="match_parent"            android:layout_height="40dp"            android:layout_weight="1"            android:background="@drawable/btn_selector_choose"            android:text="关闭对话框"            android:textColor="#ffffff"            android:textSize="20sp" />        </LinearLayout></RelativeLayout>

mainactivity代码,这个布局我就不贴了。

  public class MainActivity : Activity    {        private AlertDialog alertDialog = null;        private AlertDialog.Builder builder = null;        private Button btn_show = null;        protected override void OnCreate(Bundle bundle)        {            base.OnCreate(bundle);            SetContentView(Resource.Layout.Main);             bindViewClick();            builder = new AlertDialog.Builder(this);                     LayoutInflater layoutInflater = LayoutInflater.From(this);            var view_customer = layoutInflater.Inflate(Resource.Layout.view_dialog_custom, null, false);            builder.SetView(view_customer);            builder.SetCancelable(false);            alertDialog = builder.Create();            view_customer.FindViewById(Resource.Id.btn_cancel).Click += (s, e) =>            {                Toast.MakeText(this, "对话框已关闭", ToastLength.Short).Show();                alertDialog.Dismiss();            };            view_customer.FindViewById(Resource.Id.btn_blog).Click += delegate            {                Toast.MakeText(this, "正在访问博客", ToastLength.Short).Show();                Uri uri = Uri.Parse("http://blog.csdn.net/kebi007");                Intent intent = new Intent(Intent.ActionView, uri);                StartActivity(intent);                alertDialog.Dismiss();            };            view_customer.FindViewById(Resource.Id.btn_close).Click += delegate            {                Toast.MakeText(this, "对话框已关闭", ToastLength.Short).Show();                alertDialog.Dismiss();            };            btn_show = FindViewById<Button>(Resource.Id.btn_show);            btn_show.Click += delegate { alertDialog.Show(); };        }    }

4.当然还有更高级的自定义的对话框,后面继续...........




版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
标签列表