c# - 在 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
}
}
解决方案
据我所知,您基本上是在尝试实现 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
所以我不能保证它会起作用,但这已经比使用静态更好了。
检查这是否适合您
推荐阅读
- python - 有没有办法使用命令行中的 Inkscape 将对象排列到表格(或网格)中?
- angular - 带有 socket.io 的 Angular 自定义异步验证器
- javascript - 仅在 AJAX 调用后才知道其 ID 时如何渲染 React 组件?
- delphi - 运行导出到 Excel 的 TFlexCelReport 时出错
- android - 如何使用带有 Fuel 的异步 HTTP GET 获取响应正文
- javascript - 如何使 C3.js 样式更改仅适用于一个图表
- php - 移位操作的优先级不明确
- ios - 分段控制,更改 UIImageView(以编程方式)Swift 4/5
- scala - sbt 未能检测到新的 .scala 文件
- php - 如何在 PHP NTLM SOAP 中使用 MS Dynamics Nav Web 服务对结果进行排序?