从0开始Xamarin:控件(一)

寵の児 提交于 2020-02-05 01:35:43

概述

      Xamarin和UWP的控件比较类似,以XML文档的形式表现,基本结构如下

<RadioButton android:id="@+id/radio_red"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Red" />

      在一组XML元素中标注上控件的类型,属性,Id,但是与UWP不同,Xamarin并不能在UI设计器中直接绑定后台响应,而是在MainActivity.cs中的OnCreate()方法中添加代码来绑定事件,与QT的槽机制颇有类似。其代码结构如下

RadioButton radio_red = FindViewById<RadioButton>(Resource.Id.radio_red);

radio_red.Click += RadioButtonClick;

第一行代码将UI界面的控件通过Id好赋值给一个控件对象,然后以C#常用的+=来生成新事件(可以映射到同一事件上)。

具体控件

  RadioButton

      与RadioGroup组合使用来实现互斥单选

       实例处理事件(切换toast文本的颜色)

private void RadioButtonClick (object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender; //强制类型转换
    Toast.MakeText (this, rb.Text, ToastLength.Short).Show ();
}

  ToggleButton/Switch

    切换按钮(左侧为按键,右侧为开关)

      控件的绑定

ToggleButton togglebutton = FindViewById<ToggleButton>(Resource.Id.togglebutton);

togglebutton.Click += (o, e) => {
    if (togglebutton.Checked)
        Toast.MakeText(this, "Checked", ToastLength.Short).Show ();
    else
        Toast.MakeText(this, "Not checked", ToastLength.Short).Show ();
};   //使用lamb表达式的简易响应事件

  CheckBox

      复选框,处理方法示例如下

CheckBox checkbox = FindViewById<CheckBox>(Resource.Id.checkbox);

checkbox.Click += (o, e) => {
    if (checkbox.Checked)
        Toast.MakeText (this, "Selected", ToastLength.Short).Show ();
    else
        Toast.MakeText (this, "Not selected", ToastLength.Short).Show ();
};

CardView

      

        需要Xamarin.Android.Support.v7.CardView包的支持

结构如下

<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:padding="5dp">

    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="245dp"
        android:layout_gravity="center_horizontal"
        cardview:cardElevation="4dp"
        cardview:cardCornerRadius="5dp">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="240dp"
            android:orientation="vertical"
            android:padding="8dp">

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="190dp"
                android:id="@+id/imageView"
                android:scaleType="centerCrop" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#333333"
                android:text="Photo Title"
                android:id="@+id/textView"
                android:layout_gravity="center_horizontal"
                android:layout_marginLeft="5dp" />

        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

      其嵌套结构为:LinearLayout(布局)

                                   CardView

                                        LinearLayout(布局)

                                            Item

EditText

      富文本控件

绑定事件如下(实时捕获输入信息)

EditText edittext = FindViewById<EditText>(Resource.Id.edittext);

edittext.KeyPress += (object sender, View.KeyEventArgs e) => {
    e.Handled = false;
    if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
    {
        Toast.MakeText(this, edittext.Text, ToastLength.Short).Show();
        e.Handled = true;
    }
};

效果如图:(由toast显示已输入的文字)

导航栏设置

      位于ndroid.View.View中,有三种属性:SystemUiFlagVisible – 使导航栏可见、SystemUiFlagLowProfile – 导航栏中的控件、SystemUiFlagHideNavigation – 隐藏导航栏

DatePicker(日期选择)

      分为DatePicker小组件和DatePickerDialog

      DatePicker

        首先实现IOnDateSetListener接口:

public class DatePickerFragment : DialogFragment, DatePickerDialog.IOnDateSetListener
{
    public static readonly string TAG = "X:" + typeof (DatePickerFragment).Name.ToUpper();
    
    Action<DateTime> _dateSelectedHandler = delegate { };
    
    public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
    {
        DatePickerFragment frag = new DatePickerFragment();
        frag._dateSelectedHandler = onDateSelected;
        return frag;
    }
    
    public override Dialog OnCreateDialog(Bundle savedInstanceState)
    {
        DateTime currently = DateTime.Now;
        DatePickerDialog dialog = new DatePickerDialog(Activity, 
                                                       this, 
                                                       currently.Year, 
                                                       currently.Month - 1,
                                                       currently.Day);
        return dialog;
    }
    
    public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
        Log.Debug(TAG, selectedDate.ToLongDateString());
        _dateSelectedHandler(selectedDate);
    }
}

        绑定控件

_dateDisplay = FindViewById<TextView>(Resource.Id.date_display);
_dateSelectButton = FindViewById<Button>(Resource.Id.date_select_button);
_dateSelectButton.Click += DateSelect_OnClick;

      编写响应事件

void DateSelect_OnClick(object sender, EventArgs eventArgs)
{
    DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime time)
    {
        _dateDisplay.Text = time.ToLongDateString();
    });
        frag.Show(FragmentManager, DatePickerFragment.TAG);
}

      TimerPicker

        绑定同DatePicker,DialogFragment的实现如下

public class TimePickerFragment : DialogFragment, TimePickerDialog.IOnTimeSetListener
{
    public static readonly string TAG = "MyTimePickerFragment";
    Action<DateTime> timeSelectedHandler = delegate { };

    public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected)
    {
        TimePickerFragment frag = new TimePickerFragment();
        frag.timeSelectedHandler = onTimeSelected;
        return frag;
    }

    public override Dialog OnCreateDialog (Bundle savedInstanceState)
    {
        DateTime currentTime = DateTime.Now;
        bool is24HourFormat = DateFormat.Is24HourFormat(Activity);
        TimePickerDialog dialog = new TimePickerDialog
            (Activity, this, currentTime.Hour, currentTime.Minute, is24HourFormat);
        return dialog;
    }

    public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
    {
        DateTime currentTime = DateTime.Now;
        DateTime selectedTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, hourOfDay, minute, 0);
        Log.Debug(TAG, selectedTime.ToLongTimeString());
        timeSelectedHandler (selectedTime);
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!