在OnCreate方法之外使用UI对象

时间:2014-08-27 23:19:42

标签: c# android xamarin

我是创建Android应用程序的新手。我可以在OnCreate方法中使用AXML中的对象,但是我无法在事件处理程序radioButton_Click中使用它们。我不知道如何在事件处理程序radioButton_Click中使用它们。

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        RadioButton radioButton1 = FindViewById<RadioButton>(Resource.Id.radioButton1);
        RadioButton radioButton2 = FindViewById<RadioButton>(Resource.Id.radioButton2);
        radioButton1.Click += radioButton_Click;
        radioButton2.Click += radioButton_Click;
        //radioButton1 and radioButton2 are recognized here.
    }

    void radioButton_Click(object sender, EventArgs e)
    {
        //radioButton1 and radioButton2 are not recognized here.
        //I want to know how to use IN THIS METHOD the objects loaded from the AXML
        // in OnCreate (the two radio buttons)
    }

2 个答案:

答案 0 :(得分:0)

好吧,您可能必须将此变量创建为类成员变量。

RadioButton radioButton1;
RadioButton radiobutton2;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);
    radioButton1 = FindViewById<RadioButton>(Resource.Id.radioButton1);
    radioButton2 = FindViewById<RadioButton>(Resource.Id.radioButton2);
    radioButton1.Click += radioButton_Click;
    radioButton2.Click += radioButton_Click;
    //radioButton1 and radioButton2 are recognized here.
}

void radioButton_Click(object sender, EventArgs e)
{
    //radioButton1 and radioButton2 are not recognized here.
    //I want to know how to use IN THIS METHOD the objects loaded from the AXML
    // in OnCreate (the two radio buttons)
}

答案 1 :(得分:0)

在您的活动中,创建RadioButtons的字段(最好是私有的)。 这将有助于您在全球范围内使用它们。

注意通过FindViewById施放发现!