2017-01-18 233 views
0

我要讓把另一個按鈕的背景上的按鈕背景Xamarin

如果我單擊Button1,主要ButtonBackground圖像= Button1.Background圖像。

如果我點擊Button2,主按鈕背景圖像= Button2.Background圖像。

我想讓我的應用程序有大約80個imageButton和字符。如果我學習一種方法,我的工作必須更加簡單。

enter image description here

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> 

回答

1

你不需要多lambda表達式,而不是使用SetBackgroundResource可以使用setBackgroundDrawable/getBackgroundDrawable這Xamarin支持財產背景:

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; 
} 
+0

最完美的答案。我完全想要這種方法。謝謝。 –

+0

@MahmutBedir,如果你接受這個答案,你爲什麼不[標記此答案](http://stackoverflow.com/help/someone-answers)? –