我在BottomNavigationView的片段之一中使用了Chronometer 计时码表工作正常,但是当我选择另一个片段时,它会从00:00重新开始
如果我选择另一个片段并返回timer_fragment并且计时器显示继续时间,是否仍然存在?
Timer_Frag
private Runnable runnable = new Runnable() {
public void run() {
//
// Do the stuff
if (!resume) {
cmTimer.setBase(SystemClock.elapsedRealtime());
cmTimer.start();
} else {
cmTimer.start();
}
//
cmTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener()
{
@Override
public void onChronometerTick(Chronometer chronometer)
{
try
{
if(!resume){
long minutes = ((SystemClock.elapsedRealtime() - cmTimer.getBase())/1000) / 60;
long seconds = ((SystemClock.elapsedRealtime() - cmTimer.getBase())/1000) % 60;
elapsedTime = SystemClock.elapsedRealtime();
Log.d(TAG, "onChronometerTick: " + minutes + " : " + seconds);
}
else {
long minutes = ((elapsedTime - cmTimer.getBase())/1000) / 60;
long seconds = ((elapsedTime - cmTimer.getBase())/1000) % 60;
elapsedTime = elapsedTime + 1000;
Log.d(TAG, "onChronometerTick: " + minutes + " : " + seconds);
}
}catch (Exception e)
{
e.printStackTrace();
}
}
});
// handler.postDelayed(this, 1000);
}
};
@OnClick(R.id.btnstart)
void startTimer(){
btnStart.setEnabled(false);
runnable.run();
}
谢谢... !!!
答案 0 :(得分:0)
这是科特林的一个例子。
class HomeActivity : AppCompatActivity() {
private var mFragment1: Fragment1? = null
private var mFragment2: Fragment2? = null
.
.
.
private fun initialize() {
bottomNavigationView.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.navigation_fragment_1 -> {
if (mFragment1 == null) {
mFragment1 = Fragment1.newInstance()
addFragment(mFragment1, R.id.frameLayout, false)
} else {
showFragment(mFragment1)
hideFragment(mFragment2)
}
}
R.id.navigation_fragment_1 -> {
if (mFragment2 == null) {
mFragment2 = Fragment2.newInstance()
addFragment(mFragment2, R.id.frameLayout, false)
} else {
hideFragment(mFragment1)
showFragment(mFragment2)
}
}
}
true
}
mFragment1 = Fragment1.newInstance()
addFragment(mFragment1, R.id.frameLayout, false)
}
}
fun AppCompatActivity.hideFragment(fragment: Fragment?) {
if (fragment != null)
supportFragmentManager.beginTransaction()
.hide(fragment)
.commit()
}
fun AppCompatActivity.showFragment(fragment: Fragment?) {
if (fragment != null)
supportFragmentManager.beginTransaction()
.show(fragment)
.commit()
}