2013-01-18 130 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