Xamarin Android从具有自定义外观的数据库构建自定义动态按钮并单击事件
我正在构建一个Xamarin Android应用程序,我有一个部分需要构建自定义动态按钮。下面的方法将动态构建这些按钮,但我需要调用@drawable文件夹中的xml文件作为按钮的背景和样式,我不确定如何实现这一点。我还需要为这些按钮中的每一个创建单击事件,但我不确定如何做到这一点。下面是我的动态按钮代码Xamarin Android从具有自定义外观的数据库构建自定义动态按钮并单击事件,android,button,xamarin,xamarin.android,Android,Button,Xamarin,Xamarin.android,我正在构建一个Xamarin Android应用程序,我有一个部分需要构建自定义动态按钮。下面的方法将动态构建这些按钮,但我需要调用@drawable文件夹中的xml文件作为按钮的背景和样式,我不确定如何实现这一点。我还需要为这些按钮中的每一个创建单击事件,但我不确定如何做到这一点。下面是我的动态按钮代码 protected async override void OnResume() { base.OnResume(); Vm.ShowCurre
protected async override void OnResume()
{
base.OnResume();
Vm.ShowCurrentUser();
buttonCollection = await Vm.ShowButtons();
foreach (UserButtonLabel label in buttonCollection)
{
Button custButton = new Button(this);
custButton.Id = label.iAvailableTimeStatusID;
custButton.Text = label.nStatus;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.WrapContent);
ButtonLayout.AddView(custButton, lp);
}
}
现在我需要单击委托,但我还需要弄清楚如何调用按钮的可绘制样式。下面是我如何用xml构建按钮的
<Button
android:id="@+id/childButton"
android:layout_height="wrap_content"
android:background="@drawable/GreenButton"
android:text="Place Holder text"
style="@style/button_text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
也许有一种方法可以从不同的xml调用按钮?因此我基本上发现从逻辑和UI的角度来看,最简单的方法是创建一个只有按钮的listview。这样,UI将构建带有垂直滚动条的按钮。我使用了xml模板、适配器和适配器的逻辑。其中最重要的一点是适配器中的每个按钮都有一个单击事件 AXML CustomButton.AXML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayout1"
android:padding="4dp">
<Button
android:id="@+id/childButton"
android:layout_height="wrap_content"
android:background="@drawable/GreenButton"
android:text="Clock In"
style="@style/button_text" />
</RelativeLayout>
用于调用和实例化的活动代码
protected async override void OnResume()
{
base.OnResume();
buttonCollection = await Vm.ShowButtons();
if (buttonCollection.Count > 0)
{
listAdapter = new CustomButtonAdapter(this, buttonCollection);
ButtonListview.Adapter = listAdapter;
}
}
listview上不需要一个McClickListener,因为每个按钮都有一个click事件
public class UserButtonLabel : INotifyPropertyChanged
{
private int _iAvailableTimeStatusID;
public int iAvailableTimeStatusID
{
get
{
return _iAvailableTimeStatusID;
}
set
{
_iAvailableTimeStatusID = value;
}
}
private string _nStatus;
public string nStatus
{
get
{
return _nStatus;
}
set
{
_nStatus = value;
}
}
}
protected async override void OnResume()
{
base.OnResume();
buttonCollection = await Vm.ShowButtons();
if (buttonCollection.Count > 0)
{
listAdapter = new CustomButtonAdapter(this, buttonCollection);
ButtonListview.Adapter = listAdapter;
}
}