2013-01-18 133 views
0

这似乎是一个非常简单的问题,但由于某种原因,我发现自己找不到任何合适的答案。我所拥有的是2个按钮,其中一个按钮叠放在另一个框架布局中,当点击Button1时,它将变为不可见,并出现Button2。我想要发生的事情是几秒钟后Button2自动变为不可见,并且Button1再次可见。这是我有的一小部分代码。任何帮助将不胜感激!Android按钮设置按钮不可见不点击

button1 = (Button)findViewById(R.id.button1); 
button2 = (Button)findViewById(R.id.button2); 


     button1.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       button1.setVisibility(Button.GONE); 
       button2.setVisibility(Button.VISIBLE); 

      } 
     }); 
+0

http://stackoverflow.com/questions/1877417/how-to-set-a-timer-in-android – Simon

回答

4

比很多简单的解决方案正在这里提出的是如下:

button1 = (Button)findViewById(R.id.button1); 
button2 = (Button)findViewById(R.id.button2); 


button1.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     button1.setVisibility(Button.GONE); 
     button2.setVisibility(Button.VISIBLE); 
     button1.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       button1.setVisibility(View.VISIBLE); 
       button2.setVisibility(View.GONE); 
      } 
     }, 2000); 
    } 
}); 
+0

你先生,真棒!非常感谢你,完美无瑕! – BossWalrus

0

有很多方法可以做到这一点。

你应该实现在您的活动handler(链接到UI线程),并从一个新的线程发布sendMessageDelayed

编辑: 斯科特W.有权:在相同的逻辑,你可以使用命令

PostDelayed(Your_runnable, time_to_wait)

1

这可能是一个内部类的活动。

public class SleepTask extends AsyncTask<Void, Void, Void> 
{ 

    final Button mOne, mTwo; 

    public OnCreateTask(final Button one, final Button two) { 
      mOne = one; 
      mTwo = two; 
    } 

    protected Void doInBackground(Void... params) 
    { 
     //Surround this with a try catch, I don't feel like typing it.... 
     Thread.sleep(2000); 
    } 

    protected void onPostExecute(Void result) { 
     //This keeps us from updating a no longer relevant UI thread. 
     //Such as if your acitivity has been paused or destroyed. 
     if(!isCancelled()) 
     { 
       //This executes on the UI thread. 
       mOne.setVisible(Button.VISIBLE); 
       mTwo.setVisible(Button.GONE); 
      } 
    } 
} 

在你的活动

SleepTask mCurTask; 

    onPause() 
    { 
     super.onPause(); 
     if(mCurTask != null) 
      mCurTask.cancel(); 
    } 

在你的onClick

if(mCurTask == null) 
    { 
     button1.setVisibility(Button.GONE); 
     button2.setVisibility(Button.VISIBLE); 
     mCurTask = new SleepTask; 
     mCurTask.execute(); 
    } 

我所做的这一切都从我的头顶,所以它可能要通过月食,使其快乐推。请记住,所有生命周期调用(onCreate,onDestroy)都是在UI线程上完成的,如果您想使其安全,您应该只能访问UI线程上的mCurTask。

AsyncTasks使用起来非常好,这可能会超出你的特定情况,但它是Android中常见的模式。

+0

非常感谢您的帮助,并借给我您的知识!非常非常感谢! – BossWalrus

+1

哈哈,对于这种情况来说这太过分了,我唯一能够接受的答案是检查按钮在相应情况下的相关性,也就是将它们放在onPause中并在延迟的可运行列表中检查null。 – accordionfolder

+1

虽然有一天它会派上用场!毫无疑问! – BossWalrus