1、背景說明
有時需要在APP中動態(tài)的添加控件,因此記錄下在Xamarin中的實現(xiàn)步驟。
VS2022社區(qū)版
2、效果
3、代碼
3.1、UI代碼
UI的代碼如何
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"> <!--注意,這兒的權(quán)重是1-->
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:isScrollContainer="false"
android:padding="10dp">
<!--下面這個布局主要是方便計算的-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#34ab8b"
android:layout_margin="10dip"
android:text="添加"
android:textSize="18dp"
android:textColor="#fff"/>
<Button
android:id="@+id/btn_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#34ab8b"
android:layout_margin="10dip"
android:text="編輯"
android:textSize="18dp"
android:textColor="#fff"/>
</LinearLayout>
</LinearLayout>
3.2、實現(xiàn)代碼
活動中的代碼如下:
using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Views;
using AndroidX.AppCompat.Widget;
using AndroidX.AppCompat.App;
using Google.Android.Material.FloatingActionButton;
using Google.Android.Material.Snackbar;
using Android.Widget;
using Java.Lang;
using System.Collections.Generic;
using System.Drawing;
namespace DynamicAddControls
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private LinearLayout linearLayout;
//Button索引
private List<Button> ListBtn_Show;
//TextView索引
private List<TextView> ListText_Def;
private Button btn_add, btn_edit;
//判斷btn_edit的狀態(tài)
private int EDITSTATE = 0;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
AndroidX.AppCompat.Widget.Toolbar toolbar = FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
fab.Click += FabOnClick;
inited();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.menu_main, menu);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
int id = item.ItemId;
if (id == Resource.Id.action_settings)
{
return true;
}
return base.OnOptionsItemSelected(item);
}
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)
.SetAction("Action", (View.IOnClickListener)null).Show();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void inited()
{
linearLayout = (LinearLayout)FindViewById(Resource.Id.linearlayout);
ListBtn_Show = new List<Button>();
ListText_Def = new List<TextView>();
btn_edit = (Button)FindViewById(Resource.Id.btn_edit);
btn_add = (Button)FindViewById(Resource.Id.btn_add);
btn_add.Click += Btn_add_Click;
btn_edit.Click += Btn_edit_Click;
}
private void Btn_edit_Click(object sender, EventArgs e)
{
if (EDITSTATE == 0)
{
btn_edit.Text = "確定";
EDITSTATE = 1;
}
else if (EDITSTATE == 1)
{
btn_edit.Text = "編輯";
EDITSTATE = 0;
}
}
private void Btn_add_Click(object sender, EventArgs e)
{
addBtn();//動態(tài)添加按鈕
}
private void addBtn()
{//動態(tài)添加按鈕
//添加承載兩個按鈕的LinearLayout
LinearLayout linear_layout = new LinearLayout(this);
linear_layout.Orientation= Orientation.Horizontal;//在同一個linearLayout中水平放置兩個控件
LinearLayout.LayoutParams liParam = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.WrapContent);
linear_layout.LayoutParameters = liParam;
//添加左側(cè)的Button
Button btnShow = new Button(this);
LinearLayout.LayoutParams btnAddPar = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WrapContent,
108, 3);//設(shè)置寬高及占比
btnAddPar.SetMargins(0, 10, 0, 10);
btnShow.LayoutParameters=btnAddPar;
//設(shè)置文本及顏色
btnShow.Text=ListBtn_Show.Count + ""+ linear_layout.Id;
btnShow.SetTextColor(Android.Graphics.Color.Argb(255, 255, 255, 255));
btnShow.SetBackgroundColor(Android.Graphics.Color.Argb(255, 52, 171, 139));
btnShow.Click += BtnShow_Click;//注冊事件
linear_layout.AddView(btnShow);//把btnShow添加到linear_btn中
ListBtn_Show.Add(btnShow);//把btnShow添加到索引中
//添加右側(cè)的TextView
TextView textDef = new TextView(this);
//設(shè)置文本的格式
LinearLayout.LayoutParams btnDefPar = new LinearLayout.LayoutParams
(ViewGroup.LayoutParams.WrapContent, 108, 1);//設(shè)置寬高及占比
btnDefPar.SetMargins(0, 10, 0, 10);
textDef.LayoutParameters=btnDefPar;
textDef.Text="設(shè)為默認";
textDef.Gravity=GravityFlags.Center;
textDef.SetTextColor(Android.Graphics.Color.Argb(255, 255, 255, 255));
textDef.SetBackgroundColor(Android.Graphics.Color.Argb(255, 52, 171, 139));
textDef.Click += TextDef_Click;
linear_layout.AddView(textDef);//把textDef添加到linear_btn中
ListText_Def.Add(textDef);//把textDef添加到索引中
linearLayout.AddView(linear_layout);//把linear_btn添加到外層linearLayout中
}
//設(shè)為默認的功能
private void TextDef_Click(object sender, EventArgs e)
{
View view = sender as View;
setDef(view);//設(shè)置默認
}
private void BtnShow_Click(object sender, EventArgs e)
{
View view = sender as View;
if (EDITSTATE == 1) { }
delBtn(view);//動態(tài)刪除按鈕
}
private void setDef(View view)
{//設(shè)置默認
//遍歷索引里的所有TextView
for (int i = 0; i < ListText_Def.Count; i++)
{
ListText_Def[i].SetBackgroundColor(Android.Graphics.Color.Argb(255, 52, 171, 139));
ListText_Def[i].Text="設(shè)為默認";
if (ListText_Def[i] == view)
{
view.SetBackgroundColor(Android.Graphics.Color.Argb(255, 171, 52, 56));
ListText_Def[i].Text="默認";
}
}
}
private void delBtn(View view)
{//動態(tài)刪除按鈕
if (view == null)
{
return;
}
int position = -1;
for (int i = 0; i < ListBtn_Show.Count; i++)
{
if (ListBtn_Show[i] == view)
{
position = i;
break;
}
}
if (position >= 0)
{
ListBtn_Show.RemoveAt(position);//從索引中移除被刪除的Button
ListText_Def.RemoveAt(position);//從索引中移除被刪除的TextView
linearLayout.RemoveViewAt(position + 1);//在外出linearLayout刪除內(nèi)部指定位置所有控件
}
}
}
}
4、代碼下載
工程代碼
5、相關(guān)知識點
5.1、原理說明
界面中添加控件,就是通過AddView
方法實現(xiàn)的,方法有如下的重載版本:
public unsafe virtual void AddView(View? child)
public unsafe virtual void AddView(View? child, LayoutParams? @params)
public unsafe virtual void AddView(View? child, int index)
public unsafe virtual void AddView(View? child, int index, LayoutParams? @params)
public unsafe virtual void AddView(View? child, int width, int height)
參數(shù)child
就是要添加的控件元素;LayoutParams
代表待添加元素的樣式。但也不一定非得添加這個參數(shù),因為可以在控件的LayoutParameters
屬性中設(shè)置樣式。index
是索引,從0開始;width
和height
設(shè)置控件的大小。具體可以參考上面的代碼。
5.2、其他說明
還有一個方法是直接將樣式文件加載成View
,然后再通過addView
直接實現(xiàn)文章來源:http://www.zghlxwxcb.cn/news/detail-617810.html
//獲取視圖,其中R.layout.CodeView是xml布局
View v1 =LayoutInflater.from(context).inflate(R.layout.CodeView,null,false);
//添加視圖v1到容器v
v.addView(v1);
6、參考資料
1、Android筆記——動態(tài)添加刪除控件,及添加點擊事件,本文主要參考這一篇,其介紹通過Android實現(xiàn)動態(tài)加載,本人主要是將其轉(zhuǎn)為了C#版本
2、簡析Android 動態(tài)添加控件的幾種方式
3、關(guān)于 layout_weight,你到底知多少,這一篇主要講述UI中布局的,講得淺顯易懂,推薦文章來源地址http://www.zghlxwxcb.cn/news/detail-617810.html
到了這里,關(guān)于Xamarin.Android實現(xiàn)界面自動添加控件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!