在MainActivity
我有一个Runnable,我想将变量传递给。
我在第二个示例中尝试在TextView
中添加timerValue
Runnable()
,但这不是正确的方法。
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (timeInMilliseconds / 1000);
int mins = secs / 60;
secs = secs % 60;
int hours = mins / 60;
mins = mins % 60;
recordtimer = "Recording Time: " + String.format("%02d", hours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs);
timerValueRecord.post(new Runnable()
{
public void run()
{
timerValueRecord.setText(recordtimer);
}
});
//set yout textview to the String timer here
customHandler.postDelayed(this, 1000);
}
};
我需要它来获取TextView
,而不是使用它所使用的timerValueRecord
,例如TextView
timerValue
。
逻辑是这样的:
private Runnable updateTimerThread = new Runnable(TextView timerValue){
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (timeInMilliseconds / 1000);
int mins = secs / 60;
secs = secs % 60;
int hours = mins / 60;
mins = mins % 60;
recordtimer = "Recording Time: " + String.format("%02d", hours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs);
timerValue.post(new Runnable()
{
public void run()
{
timerValue.setText(recordtimer);
}
});
//set yout textview to the String timer here
customHandler.postDelayed(this, 1000);
}
};
答案 0 :(得分:8)
创建一个实现Runnable的类,让类的构造函数接受输入,或者提供setter来设置值。一种方法是:
public class UpdateTimerThread implements Runnable {
protected TextView timerValue;
public UpdateTimerThread(TextView timerValue) {
this.timerValue= timerValue;
}
public void run() {
....
// you can access timerValue here
}
}
private Runnable updateTimerThread = new UpdateTimerThread(timerValue);
答案 1 :(得分:3)
创建另一个类(如建议的)效果很好。或者,您可以使用匿名内部类。这样的类可以访问包含它的任何Auth::user()
变量。如,
<ul>
@if (Auth::guest())
<li><a href="/guest/login">Login to the site</a></li>
<li><a href="/guest/register">Register</a></li>
@else
@if ($user->type == 'admin')
<li><a href="/admin/dashboard">Home Page</a></li>
<li><a href="/admin/users">Users</a></li>
...
@elseif ($user->type == 'instructor')
<li><a href="/instructor/dashboard">Home Page</a></li>
<li><a href="/instructor/students">Students</a></li>
...
@elseif ($user->type == 'student')
<li><a href="/student/dashboard">Home Page</a></li>
<li><a href="/student/lessons">Lessons</a></li>
...
@endif
@endif
</ul>