单击多个页面的事件

时间:2017-11-11 20:14:06

标签: c# android xamarin visual-studio-2017

如何将点击事件分配给具有多个页面的应用中的按钮?

我可以使用单页应用程序完成,如下所示:

namespace Welf
{
    [Activity(Label = "Welf", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Assign click event to direct to next page (page1)
            Button cmdFirst = FindViewById<Button>(Resource.Id.cmdFirst);
            cmdFirst.Click += delegate
            {
                SetContentView(Resource.Layout.page1);
            };
        }
    }
}

但是我在什么时候为其他页面上的按钮指定了点击事件?

如果我执行以下操作它不起作用,我猜测因为页面没有实例化,所以FindByView返回null:

    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Assign click event to direct to next page (page1)
            Button cmdFirst = FindViewById<Button>(Resource.Id.cmdFirst);
            cmdFirst.Click += delegate
            {
                SetContentView(Resource.Layout.page1);
            };

            // This assignment doesn't work
            Button cmdSecond = FindViewById<Button>(Resource.Id.cmdSecond);
            cmdSecond.Click += delegate
            {
                SetContentView(Resource.Layout.page3);
            }
        }
    }

...以下内容确实有效,但是我在重复访问同一页面时遇到了麻烦,因为我是第二次添加该事件:

    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Assign click event to direct to next page (page1)
            Button cmdFirst = FindViewById<Button>(Resource.Id.cmdFirst);
            cmdFirst.Click += delegate
            {
                SetContentView(Resource.Layout.page1);

                // This click works the first time only, for obvious reasons
                Button cmdSecond = FindViewById<Button>(Resource.Id.cmdSecond);
                cmdSecond.Click += delegate
                {
                    SetContentView(Resource.Layout.page3);
                }
            };
        }
    }

那我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

您应该只在任何活动中调用一次SetContentView()。你需要做的是做一个新的活动。 1:右键单击您的项目,然后单击新项目。 2:创建新活动和新的Android布局。 3:然后在新的Activity.cs中为您刚创建的新布局调用SetContentView。 4:然后使用此代码调用您的新活动:Intent intent = new Intent(this,typeof(mynewactivityname)); StartActivity(intent);

相关问题