创建布局-弹出浮动框Toast

本节课,我们在布局xaml种添加一个按钮button,然后给按钮注册一个点击事件,当用户点击按钮的是,弹出一个消息框,显示一个文本。

布局axml + MainActivity.cs,点击按钮弹出Toast,拓展PopupWindow弹窗

布局文件

Resources/layout/activity_main.axml

<?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="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="点我"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/MyButton" />
</LinearLayout>Code language: HTML, XML (xml)

MainActivity.cs 代码

using Android.App;
using Android.OS;
using Android.Widget;
using AndroidX.AppCompat.App;
using Android.Views;

namespace PopupDemo
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            //绑定按钮
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            button.Click += Button_Click;
        }

        private void Button_Click(object sender, System.EventArgs e)
        {
            //原来简单Toast效果
            Toast.MakeText(this, "FoxDevelop", ToastLength.Long).Show();
        }
    }
}Code language: HTML, XML (xml)

注意

  1. ShowAsDropDown(View anchor):依附在按钮下方弹出浮动窗口
  2. SetFocusable(true):获取焦点,点击弹窗外部区域可以关闭窗口
  3. Toast:简单轻量提示;
  4. axml里面id和C#代码必须完全一致:@+id/MyButton,C#用Resource.Id.MyButton

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注