在OnCreate外部设置EditText.Text

时间:2018-05-03 07:15:19

标签: c# android xamarin xamarin.android

我有一个非常简单的应用程序,目前只包含两个类 - 这些是" MainActivity.cs "和" NewDate.cs "

MainActivity简单地挂钩按钮和editText控件,然后调用" NewDate.NewTimer()" - 这只是开始一个.NET计时器实例。

Inside" 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;
    } 
}

NewDate.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
    }
}

1 个答案:

答案 0 :(得分:0)

从我看到的,你基本上是在尝试实现一个ViewModel模式。

由于您是初学者,这可能有点复杂,但是当您准备好时,请查看some tutorial

从现在开始,去寻找更简单的东西,并将你的逻辑放在你的活动中

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所以我不能保证它会起作用,但这已经比使用静态更好了。

检查这是否适合您