首页 > 解决方案 > 在 OnCreate 之外设置 EditText.Text

问题描述

我有一个非常简单的应用程序,目前只包含两个类——它们是“ MainActivity.cs ”和“ NewDate.cs

MainActivity 简单地连接了一个按钮和一个 editText 控件,然后调用“ NewDate.NewTimer() ”——这只是一个 .NET 计时器实例的开始。

在“OnCreate”中,当用户单击按钮时,我能够成功设置 EditText 的值,但是,当计时器到期时,我调用

     SafeDate.MainActivity.SetTimerDoneText("Timer done!"); 

使用断点我可以确定应用程序正在通过“SetTimerDoneText”运行,但是该行

 editTimerInfo.Text = Text;

不起作用。

任何帮助将不胜感激。

以下两个类:

MainActivity.cs

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

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        Button btnNewTimer = FindViewById<Button>(Resource.Id.newDate);
         editTimerInfo = FindViewById<EditText>(Resource.Id.editTimerInfo);
        btnNewTimer.Click += (sender, e) =>
        {
            // Translate user's alphanumeric phone number to numeric
            Core.NewDate.NewTimer();
           // editTimerInfo.Text = "Timer started!"; //this works
        };
    }

    public static void SetTimerDoneText(string Text)
    {
        //SetContentView(Resource.Layout.Main);//commented out - doesn't work
        //   EditText editTimerInfo = FindViewById<EditText>(Resource.Id.editTimerInfo); //commented out - doesn't work
        editTimerInfo.Text = Text;
    } 
}

新日期.cs

public static class NewDate
{

    public static void NewTimer()
    {

        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 5000; //Miliseconds : 5000 = 1 second
        aTimer.Enabled = true;
    }

    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        SafeDate.MainActivity.SetTimerDoneText("Timer done!"); //Successfully enters the function in MainActivity.cs but won't set the EditText value
    }
}

标签: c#androidxamarinxamarin.android

解决方案


据我所知,您基本上是在尝试实现 ViewModel 模式。

由于您是初学者,因此掌握起来可能有点复杂,但是当您准备好时,请看一些教程

从现在开始,做一些更简单的事情,把你的逻辑放在你的活动中

btnNewTimer.Click += (sender, e) =>
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000; //Miliseconds : 5000 = 1 sec
    aTimer.Enabled = true;
};

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    editTimerInfo.Text = "Timer done!"; //Successfully enters the function in MainActivity.cs but won't set the EditText value
}

我从来没有玩过,Timers所以我不能保证它会起作用,但这已经比使用静态更好了。

检查这是否适合您


推荐阅读