第一步先在MainActivity.cs 文件把当前Activity 获取。注意:Xamarin.Form是可以直接调用安卓原生方法的,有些伙伴可能比较迷茫
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);//获取当前的活动视图
LoadApplication(new App());
}
}
然后创建Layout文件,
xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:minWidth="200dp"
android:padding="10dp"
android:paddingTop="30dp"
android:paddingBottom="30dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="小区名称"
android:minHeight="45dp" />
<ImageView
android:src="@android:color/holo_blue_light"
android:layout_width="match_parent"
android:layout_height="200dp" />
<Button
android:text="提交"
android:minHeight="45dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
然后再创建对应的cs文件;
using Android.App;
using Android.Content;
using Lierda.HandApp.Droid;
public class CreateAreaInformation : Dialog
{
public Context context { get; private set; }
public CreateAreaInformation(Context context) : base(context)
{
this.context = context;
}
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
this.SetContentView(Resource.Layout.CreateAreaInformationDialog);
var dialogWindow = this.Window;
var act = context as Activity;
var manager = act.WindowManager;
var display = manager.DefaultDisplay;
var attr = dialogWindow.Attributes;
#pragma warning disable CS0618 // Type or member is obsolete
attr.Width = (int)(display.Width * 0.8);
#pragma warning restore CS0618 // Type or member is obsolete
dialogWindow.Attributes = attr;
base.OnCreate(savedInstanceState);
}
}
这里需要继承Dialog 类,注意命名空间,别弄错了。
最后便是调用了。
/// <summary>
/// 单击新增小区
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Handle_Clicked(object sender, System.EventArgs e)
{
//注意,Xamarin.Forms.Forms.Context便是当前活动。
CreateAreaInformation createAreaInformation = new CreateAreaInformation(Xamarin.Forms.Forms.Context);
createAreaInformation.Show();
}
效果如下: