65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 SQLite 和自定义 ListView 的 Xamarin Android 应用

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (20投票s)

2016年4月6日

CPOL

5分钟阅读

viewsIcon

62973

downloadIcon

1718

本教程将解释如何使用 Visual Studio 提供的 Xamarin 工具开发 Android 应用。本文将引导您创建一个与通讯录相关的小型 Android 应用。

引言

阅读本教程后,您将能够了解
  • 如何在 Visual Studio 中创建 Android 项目并在 Visual Studio IDE 中设置 JDK 和 Android SDK 位置。如何创建样式并将其应用于布局组件
  • 如何创建 SQLite 数据库并执行 CRUD 操作
  • 如何创建自定义 ListView 并对其进行一些操作
  • 如何使用 Intent 在活动之间传递值
为了您的更好理解,我正在创建一个通讯录应用,它将具有显示联系人列表、根据联系人姓名搜索联系人、创建新联系人、编辑现有联系人信息和删除联系人的功能。以下快照显示了我们正在创建的应用的外观
 
快照 1:联系人列表屏幕

 

快照 2:添加新联系人或编辑现有联系人的表单

 

快照 3:删除联系人

 
设置 JDK 和 Android SDK 位置

在创建您的第一个应用之前,您首先需要确保 Xamarin 的 Android 设置是否正确。您可以在 Microsoft Visual Studio 启动页上的 工具->选项->Xamarin->Android 设置 中检查。此外,如果需要,您可以更改 JDK 和 Android SDK 的位置。

 
现在创建一个新的 Xamarin 项目,您可以通过在新项目窗口中选择“空白应用”选项来创建空白项目。一个包含 Assets 和 Resources 文件夹的默认项目已准备就绪。此外,最初您可以通过右键单击解决方案资源管理器中的项目和属性来更改基本应用程序属性,例如“要编译的 Android 版本”、“最小 Android 目标版本”和“默认目标版本”。
 

通讯录的 SQLite 数据库

添加一个新的类 AddressBookDbSelper.cs 并使其继承自 SQLiteOpenHelper 基类。在这个类中,我将编写代码在 OnCreate 方法中创建一个名为 AddressBook 的表,然后编写一些方法来选择、插入、更新和删除联系人。
  • GetAllContacts(): 从数据库中检索所有可用联系人。
  • GetContactsBySearchName(string nameToSearch): 根据传入的搜索参数 nameToSearch 读取联系人。
  • AddNewContact(AddressBook contactinfo): 插入新的联系人信息。
  • UpdateContact(AddressBook contitem): 根据 AddressBook 类的 Id 属性更新现有联系人。
  • DeleteContact(string  contactId): 根据联系人 Id 删除现有联系人。

 

  public class AddressBookDbHelper: SQLiteOpenHelper
    {
        private const string APP_DATABASENAME = "Student.db3";
        private const int APP_DATABASE_VERSION = 1;

        public AddressBookDbHelper(Context ctx):
            base(ctx, APP_DATABASENAME, null, APP_DATABASE_VERSION)
        {

        }

        public override void OnCreate(SQLiteDatabase db)
        {
            db.ExecSQL(@"CREATE TABLE IF NOT EXISTS AddressBook(
                            Id INTEGER PRIMARY KEY AUTOINCREMENT,
                            FullName TEXT NOT NULL,
                            Mobile  TEXT NOT NULL,
                            Email   TEXT NULL,
                            Details TEXT)");

            db.ExecSQL("Insert into AddressBook(FullName,Mobile,Email,Details)VALUES('Sharad Chandra Pyakurel','9851162459','sharad.pyakurel@gmail.com','this is details')");
            
            db.ExecSQL("Insert into AddressBook(FullName,Mobile,Email,Details)VALUES('Gopal Prasad','9841258963','gopal.pyakurel@gmail.com','this is details')");

        }

        public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            db.ExecSQL("DROP TABLE IF EXISTS AddressBook");
            OnCreate(db);
        }

        //Retrive All Contact Details
        public IList<AddressBook> GetAllContacts()
        {

            SQLiteDatabase db = this.ReadableDatabase;

           ICursor c =  db.Query("AddressBook", new string[] { "Id", "FullName", "Mobile", "Email", "Details" }, null, null, null, null, null);

            var contacts = new List<AddressBook>();

            while (c.MoveToNext())
            {
                contacts.Add(new AddressBook
                        {
                            Id = c.GetInt(0),
                            FullName = c.GetString(1),
                            Mobile = c.GetString(2),
                            Email = c.GetString(3),
                            Details = c.GetString(4) }); 
            }

            c.Close();
            db.Close();

            return contacts;
        }


        //Retrive All Contact Details
        public IList<AddressBook> GetContactsBySearchName(string nameToSearch)
        {

            SQLiteDatabase db = this.ReadableDatabase;

            ICursor c = db.Query("AddressBook", new string[] { "Id", "FullName", "Mobile", "Email", "Details" }, "upper(FullName) LIKE ?", new string[] {"%"+ nameToSearch.ToUpper() +"%"}, null, null, null, null);

            var contacts = new List<AddressBook>();

            while (c.MoveToNext())
            {
                contacts.Add(new AddressBook
                {
                    Id = c.GetInt(0),
                    FullName = c.GetString(1),
                    Mobile = c.GetString(2),
                    Email = c.GetString(3),
                    Details = c.GetString(4)
                });
            }

            c.Close();
            db.Close();

            return contacts;
        }

        //Add New Contact
        public void AddNewContact(AddressBook contactinfo)
        {
            SQLiteDatabase db = this.WritableDatabase;
            ContentValues vals = new ContentValues();
            vals.Put("FullName", contactinfo.FullName);
            vals.Put("Mobile", contactinfo.Mobile);
            vals.Put("Email", contactinfo.Email);
            vals.Put("Details", contactinfo.Details);
            db.Insert("AddressBook", null, vals);
        }

        //Get contact details by contact Id
        public ICursor getContactById(int id)
        {
            SQLiteDatabase db = this.ReadableDatabase;
            ICursor res = db.RawQuery("select * from AddressBook where Id=" + id + "", null);
            return res;
        }

        //Update Existing contact
        public void UpdateContact(AddressBook contitem)
        {
            if (contitem == null)
            {
                return;
            }

            //Obtain writable database
            SQLiteDatabase db = this.WritableDatabase;

            //Prepare content values
            ContentValues vals = new ContentValues();
            vals.Put("FullName", contitem.FullName);
            vals.Put("Mobile", contitem.Mobile);
            vals.Put("Email", contitem.Email);
            vals.Put("Details", contitem.Details);


            ICursor cursor = db.Query("AddressBook",
                    new String[] {"Id", "FullName", "Mobile", "Email", "Details" }, "Id=?", new string[] { contitem.Id.ToString() }, null, null, null, null);

            if (cursor != null)
            {
                if (cursor.MoveToFirst())
                {
                    // update the row
                    db.Update("AddressBook", vals, "Id=?", new String[] { cursor.GetString(0) });
                }

                cursor.Close();
            }

        }


        //Delete Existing contact
        public void DeleteContact(string  contactId)
        {
            if (contactId == null)
            {
                return;
            }

            //Obtain writable database
            SQLiteDatabase db = this.WritableDatabase;

            ICursor cursor = db.Query("AddressBook",
                    new String[] { "Id", "FullName", "Mobile", "Email", "Details" }, "Id=?", new string[] { contactId }, null, null, null, null);

            if (cursor != null)
            {
                if (cursor.MoveToFirst())
                {
                    // update the row
                    db.Delete("AddressBook", "Id=?", new String[] { cursor.GetString(0) });
                }

                cursor.Close();
            }

        }
        


    }

AddressBook 类包含以下属性,这些属性与 AddressBook 表中的列匹配

   public class AddressBook
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
        public string Details { get; set; }

        public static explicit operator AddressBook(Java.Lang.Object v)
        {
            throw new NotImplementedException();
        }
    }

 

为 ListView 创建 ListView 和自定义基本适配器

联系人列表将填充到列表视图中。在 ListView 的顶部添加了两个按钮用于“添加新联系人”和“搜索”,以及一个用于输入搜索参数的 EditText。descendantFocusability="beforeDescendants" 确保此视图在任何子视图之前获得焦点。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:paddingBottom="1dp"
    android:paddingLeft="1dp"
    android:paddingRight="1dp"
    android:paddingTop="0dp">
    <TableLayout
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableRow>
            <Button
                android:id="@+id/contactList_btnAdd"
                style="@style/button_style"
                android:layout_weight="1"
                android:text="Add New Contact" />
        </TableRow>
        <TableRow>
            <EditText
                android:id="@+id/contactList_txtSearch"
                style="@style/input_style"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="Search" />
            <Button
                android:id="@+id/contactList_btnSearch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#0f87ff"
                android:layout_marginRight="1dp"
                android:paddingTop="9dp"
                android:paddingBottom="9dp"
                android:text="Search"
                android:textAlignment="center"
                android:textAllCaps="false"
                android:minHeight="0dp"
                android:textColor="#fff"
                android:textSize="15sp" />
        </TableRow>
    </TableLayout>
    <ListView
        android:id="@+id/contactList_listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tableLayout"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:clickable="true"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />
</RelativeLayout>
此 id 将用于从 activity cs 文件中初始化它。我们需要为 ListView 行中的项目创建单独的 xml 文件。列表行布局将定义列表行项目的布局。此布局将由自定义列表适配器使用。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/list_selector"
    android:orientation="vertical"
    android:padding="2dp">

    <TableLayout
        android:layout_width="fill_parent"
        android:padding="3dp"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Name: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_fullName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="Full Name"
                android:textColor="#0000dd"
                android:textSize="15dp"
                android:textStyle="bold" />
        </TableRow>


        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Mobile: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_mobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="Mobile"
                android:textColor="#0000dd"
                android:textSize="15dip"
                android:textStyle="bold" />

        </TableRow>

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Email: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="Email"
                android:textColor="#0000dd"
                android:textSize="15dp" />
        </TableRow>


        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Description: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_descriptin"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="description"
                android:textColor="#0000dd"
                android:textSize="15dp" />
        </TableRow>




    </TableLayout>

  <ImageView 
    android:id="@+id/lr_deleteBtn"
    android:layout_width="50dip" 
    android:layout_height="100dip"
    android:src="@drawable/delete"
      android:layout_alignParentRight="true"
          android:clickable="true"
    />


</RelativeLayout>

由于我们正在创建一个自定义 ListView,我们现在需要创建一个自定义适配器。这个自定义适配器将扩展一个泛型基本适配器 AddressBook。这个适配器的构造函数接受一个 Activity 作为上下文和一个 AddressBook 类型的 List。适配器将数据对象列表作为输入,列表中的每个对象都映射到列表行。适配器还膨胀要为每个行项目渲染的布局。这是创建自定义 ListView 中最重要和最棘手的部分。
    [Activity(Label = "ContactListBaseAdapter")]
    public partial class ContactListBaseAdapter : BaseAdapter<AddressBook>
    {
        IList<AddressBook> contactListArrayList;
        private LayoutInflater mInflater;
        private Context activity;
        public ContactListBaseAdapter(Context context,
                                                IList<AddressBook> results)
        {
            this.activity = context;
            contactListArrayList = results;
            mInflater = (LayoutInflater)activity.GetSystemService(Context.LayoutInflaterService);
        }

        public override int Count
        {
            get { return contactListArrayList.Count; }
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        public override AddressBook this[int position]
        {
            get { return contactListArrayList[position]; }
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            ImageView btnDelete;
            ContactsViewHolder holder = null;
            if (convertView == null)
            {
                convertView = mInflater.Inflate(Resource.Layout.list_row_contact_list, null);
                holder = new ContactsViewHolder();

                holder.txtFullName = convertView.FindViewById<TextView>(Resource.Id.lr_fullName);
                holder.txtMobile = convertView.FindViewById<TextView>(Resource.Id.lr_mobile);
                holder.txtEmail = convertView.FindViewById<TextView>(Resource.Id.lr_email);
                holder.txtDescription = convertView.FindViewById<TextView>(Resource.Id.lr_descriptin);
                btnDelete = convertView.FindViewById<ImageView>(Resource.Id.lr_deleteBtn);

                btnDelete.Click += (object sender, EventArgs e) =>
                {

                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    AlertDialog confirm = builder.Create();
                    confirm.SetTitle("Confirm Delete");
                    confirm.SetMessage("Are you sure delete?");
                    confirm.SetButton("OK", (s, ev) =>
                    {
                        var poldel = (int)((sender as ImageView).Tag);

                        string id = contactListArrayList[poldel].Id.ToString();
                        string fname = contactListArrayList[poldel].FullName;

                        contactListArrayList.RemoveAt(poldel);

                        DeleteSelectedContact(id);
                        NotifyDataSetChanged();

                        Toast.MakeText(activity, "Contact Deeletd Successfully", ToastLength.Short).Show();
                    });
                    confirm.SetButton2("Cancel", (s, ev) =>
                    {

                    });

                    confirm.Show();
                };

                convertView.Tag = holder;
                btnDelete.Tag = position;
            }
            else
            {
                btnDelete = convertView.FindViewById<ImageView>(Resource.Id.lr_deleteBtn);
                holder = convertView.Tag as ContactsViewHolder;
                btnDelete.Tag = position;
            }

            holder.txtFullName.Text = contactListArrayList[position].FullName.ToString();
            holder.txtMobile.Text = contactListArrayList[position].Mobile;
            holder.txtEmail.Text = contactListArrayList[position].Email;
            holder.txtDescription.Text = contactListArrayList[position].Details;

            if (position % 2 == 0)
            {
                convertView.SetBackgroundResource(Resource.Drawable.list_selector);
            }
            else
            {
                convertView.SetBackgroundResource(Resource.Drawable.list_selector_alternate);
            }

            return convertView;
        }

        public IList<AddressBook> GetAllData()
        {
            return contactListArrayList;
        }

        public class ContactsViewHolder : Java.Lang.Object
        {
            public TextView txtFullName { get; set; }
            public TextView txtMobile { get; set; }
            public TextView txtEmail { get; set; }
            public TextView txtDescription { get; set; }
        }

        private void DeleteSelectedContact(string contactId)
        {
            AddressBookDbHelper _db = new AddressBookDbHelper(activity);
            _db.DeleteContact(contactId);
        }

    }
ContactViewHolder 使您无需查找即可访问每个列表项视图。它表示列表行中的项目。您必须在 BaseAdapter 类实现中覆盖 Count、GetItemId 和 GetView 方法。Count 方法表示列表中的总行数,GetItemId 表示列表中每个项目的唯一 ID。GetView 为每个列表行膨胀布局并在屏幕上渲染。为了实现列表视图行上的删除功能,管理删除按钮点击事件的代码放置在 GetView 方法中。删除按钮的标签将决定要删除的行的位置。行的位置除以 2 以查找 ListView 中的备用行并相应地应用样式。

将自定义适配器设置为 ListView

一旦我们的自定义适配器准备好,我们需要实例化此适配器以将其设置为 ListView。

    [Activity(Label = "Contact List", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        Button btnAdd, btnSearch;
        EditText txtSearch;
        ListView lv;
        IList<AddressBook> listItsms = null;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            btnAdd = FindViewById<Button>(Resource.Id.contactList_btnAdd);
            btnSearch = FindViewById<Button>(Resource.Id.contactList_btnSearch);
            txtSearch = FindViewById<EditText>(Resource.Id.contactList_txtSearch);
            lv = FindViewById<ListView>(Resource.Id.contactList_listView);

            btnAdd.Click += delegate
            {
                var activityAddEdit = new Intent(this, typeof(AddEditAddressBookActivity));
                StartActivity(activityAddEdit);

            };

            btnSearch.Click += delegate
              {
                  LoadContactsInList();
              };

            LoadContactsInList();

        }

        private void LoadContactsInList()
        {
            AddressBookDbHelper dbVals = new AddressBookDbHelper(this);
            if (txtSearch.Text.Trim().Length < 1)
            {
                listItsms = dbVals.GetAllContacts();
            }
            else {

                listItsms = dbVals.GetContactsBySearchName(txtSearch.Text.Trim());
            }

            lv.Adapter = new ContactListBaseAdapter(this, listItsms);

            lv.ItemLongClick += lv_ItemLongClick;
        }

        private void lv_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
        {
            AddressBook o = listItsms[e.Position];

            var activityAddEdit = new Intent(this, typeof(AddEditAddressBookActivity));
            activityAddEdit.PutExtra("ContactId", o.Id.ToString());
            activityAddEdit.PutExtra("ContactName", o.FullName);
            StartActivity(activityAddEdit);
        }

    }

我们创建了 lv_ItemLongClick 回调来处理 ListView 长按事件。当我们长按 ListView 中的项目时,选定的联系人将在新窗口中打开以进行编辑,并填充现有信息。指示编辑模式的值使用 intent PutExtra 方法传递。

 

添加或编辑联系人

与添加新联系人或编辑现有联系人相关的设计布局写在以下代码块中。此布局的设计视图显示在以下代码块下方。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:scrollbars="none">
        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <TableRow
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Contact Id " />
                <EditText
                    android:id="@+id/addEdit_ContactId"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:editable="false"
                    android:hint="Contact Id" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Full Name " />
                <EditText
                    android:id="@+id/addEdit_FullName"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_ContactId"
                    android:layout_weight="1"
                    android:hint="Full Name" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Mobile" />
                <EditText
                    android:id="@+id/addEdit_Mobile"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_FullName"
                    android:layout_weight="1"
                    android:hint="Mobile" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Email" />
                <EditText
                    android:id="@+id/addEdit_Email"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_Mobile"
                    android:layout_weight="1"
                    android:hint="Email" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Description" />
                <EditText
                    android:id="@+id/addEdit_Description"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_Email"
                    android:layout_weight="1"
                    android:gravity="top|left"
                    android:hint="Description"
                    android:inputType="textMultiLine"
                    android:lines="4"
                    android:scrollHorizontally="false"
                    android:scrollbars="vertical" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=" " />
                <Button
                    android:id="@+id/addEdit_btnSave"
                    style="@style/button_style"
                    android:layout_weight="1"
                    android:text=" Save " />
            </TableRow>
        </TableLayout>
    </ScrollView>
</RelativeLayout>

 

通常,为各种控件(例如 EditText、Button,甚至是整个表单)应用一些视觉样式是一个好主意。通常,可以使用我们添加到 drawable 中的资源 xml 或图像文件来应用一些基本样式。但是我们可以创建单独的样式文件,以 xml 文件的形式指定适当的样式,例如大小、颜色、边距、背景等。用于将样式应用于控件的 style.xml 的 xml 代码如下

<resources>

  <style name="input_style">
    <item name="android:background">@drawable/input_shape</item>
    <item name="android:layout_marginTop">1dp</item>
    <item name="android:layout_marginRight">10dp</item>
    <item name="android:layout_marginBottom">7dp</item>
    <item name="android:paddingLeft">8dp</item>
    <item name="android:paddingTop">9dp</item>
    <item name="android:paddingBottom">9dp</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#000</item>
  </style>

  <style name="button_style">
    <item name="android:background">@drawable/button_shape</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_margin">1dp</item>
    <item name="android:paddingLeft">5dp</item>
    <item name="android:paddingRight">5dp</item>
    <item name="android:paddingTop">9dp</item>
    <item name="android:paddingBottom">9dp</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#fff</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:minHeight">35dp</item>
  </style>
</resources>

通过 Intent.GetStringExtra("ContactId") ?? string.Empty 接收到的值将决定联系人的保存模式。如果我们获得正的 Intent.GetStringExtra 值,则特定 Id 的现有联系人信息将由 LoadDataForEdit(string contactId) 方法加载,从而指示编辑模式。如果该值为空,则活动将以新条目模式打开。

    [Activity(Label = "Add/Edit Contacts")]
    public class AddEditAddressBookActivity : Activity
    {
        EditText txtId, txtFullName, txtMobile, txtEmail, txtDescription;
        Button btnSave;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AddEditContacts);

            txtId = FindViewById<EditText>(Resource.Id.addEdit_ContactId);
            txtFullName = FindViewById<EditText>(Resource.Id.addEdit_FullName);
            txtMobile = FindViewById<EditText>(Resource.Id.addEdit_Mobile);
            txtEmail = FindViewById<EditText>(Resource.Id.addEdit_Email);
            txtDescription = FindViewById<EditText>(Resource.Id.addEdit_Description);
            btnSave = FindViewById<Button>(Resource.Id.addEdit_btnSave);

            btnSave.Click += buttonSave_Click;

            string editId = Intent.GetStringExtra("ContactId") ?? string.Empty;

            if (editId.Trim().Length > 0)
            {
                txtId.Text = editId;
                LoadDataForEdit(editId);
            }
        }

        private void LoadDataForEdit(string contactId)
        {
            AddressBookDbHelper db = new AddressBookDbHelper(this);
            ICursor cData = db.getContactById(int.Parse(contactId));
            if (cData.MoveToFirst())
            {
                txtFullName.Text = cData.GetString(cData.GetColumnIndex("FullName"));
                txtMobile.Text = cData.GetString(cData.GetColumnIndex("Mobile"));
                txtEmail.Text = cData.GetString(cData.GetColumnIndex("Email"));
                txtDescription.Text = cData.GetString(cData.GetColumnIndex("Details"));
            }
        }

        void buttonSave_Click(object sender, EventArgs e)
        {
            AddressBookDbHelper db = new AddressBookDbHelper(this);
            if (txtFullName.Text.Trim().Length < 1)
            {
                Toast.MakeText(this, "Enter Full Name.", ToastLength.Short).Show();
                return;
            }

            if (txtMobile.Text.Trim().Length < 1)
            {
                Toast.MakeText(this, "Enter Mobile Number.", ToastLength.Short).Show();
                return;
            }

            if (txtEmail.Text.Trim().Length > 0)
            {
                string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                if (!Regex.IsMatch(txtEmail.Text, EmailPattern, RegexOptions.IgnoreCase))
                {
                    Toast.MakeText(this, "Invalid email address.", ToastLength.Short).Show();
                    return;
                }
            }

            AddressBook ab = new AddressBook();

            if (txtId.Text.Trim().Length > 0)
            {
                ab.Id = int.Parse(txtId.Text);
            }
            ab.FullName = txtFullName.Text;
            ab.Mobile = txtMobile.Text;
            ab.Email = txtEmail.Text;
            ab.Details = txtDescription.Text;

            try
            {

                if (txtId.Text.Trim().Length > 0)
                {
                    db.UpdateContact(ab);
                    Toast.MakeText(this, "Contact Updated Successfully.", ToastLength.Short).Show();
                }
                else
                { 
                    db.AddNewContact(ab);
                    Toast.MakeText(this, "New Contact Created Successfully.", ToastLength.Short).Show();
                }

                Finish();

                //Go to main activity after save/edit
                var mainActivity = new Intent(this, typeof(MainActivity));
                StartActivity(mainActivity);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
          
        }
    }

 

请访问我的 YouTube 频道:https://www.youtube.com/channel/UCYESe2tTh9G6temYeaPNwwA

我将在我的 Google 博客上发布一些文章:http://sharadpyakurel.blogspot.com

 

 

 
© . All rights reserved.