我想制作
如果我单击Button1,主ButtonBackground图像= Button1.Background图像。
如果我单击Button2,主按钮背景图像= Button2.Background图像。
我想让我的应用程序拥有大约80个imageButton和角色。如果我学习一种方法,我的工作必须更加轻松。
My.cs
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.layout1);
Button btn1 = (Button)FindViewById(Resource.Id.btn1);
Button btn2 = (Button)FindViewById(Resource.Id.btn2);
Button btnMain = (Button)FindViewById(Resource.Id.btnMain);
btn1.Click += delegate {
btnMain.SetBackgroundResource(/*I cant fill in method*/);
};
btn2.Click += delegate {
btnMain.SetBackgroundResource(/*I cant fill in method*/);
};
}
layout1.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:text="Button 1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:background="@drawable/btn_yellow" />
<Button
android:text="Button 2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:background="@drawable/btn_green" />
<Button
android:text="Main Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnMain" />
</LinearLayout>
答案 0 :(得分:1)
您不需要多个lambdas,而不是使用SetBackgroundResource,您可以使用setBackgroundDrawable / getBackgroundDrawable,它在Xamarin中支持属性Background:
Button btnMain;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.layout1);
Button btn1 = (Button)FindViewById(Resource.Id.btn1);
Button btn2 = (Button)FindViewById(Resource.Id.btn2);
btnMain = (Button)FindViewById(Resource.Id.btnMain);
btn1.Click += ChangeBackground;
btn2.Click += ChangeBackground;
}
private void ChangeBackground(object sender, EventArgs e)
{
var btn = sender as Button;
btnMain.Background = btn.Background;
}