2013-10-10 41 views
0

我有一個由「設置」按鈕激活並可以通過「取消」按鈕停止的CountDownTimer。如何以編程方式更改按鈕的重量

活動開始時,我只想顯示設置按鈕。倒計時開始後,我想隱藏「設置」按鈕並顯示「取消」按鈕。

我想通過改變按鈕的重量來做到這一點。我該怎麼做呢?我發現了類似的問題,當我嘗試它們時,這些問題的答案不起作用。我認爲這些答案只是完整代碼的片段,這正是我正在尋找的。

這裏是XML:

<LinearLayout 
    android:id="@+id/buttonsContainer" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" > 
     <Button 
      android:id="@+id/setDelay" 
      android:layout_width="0dip" 
      android:layout_height="fill_parent" 
      android:layout_weight="1" 
      android:onClick="activateDelay" 
      android:text="Set Delay" /> 
     <Button 
      android:id="@+id/cancelDelay" 
      android:layout_width="0dip" 
      android:layout_height="fill_parent" 
      android:layout_weight="1" 
      android:onClick="cancelDelay" 
      android:text="Cancel Delay" /> 
</LinearLayout> 

我知道我使用硬編碼字符串,它們只是用於開發目的。

回答

3

爲什麼要使用weight屬性來隱藏按鈕? layout_weight用於按比例分配空間(根據給定的權重)。我猜你可能通過將layout_weight設置爲0(而另一個上的權重大於0)來「隱藏」一個按鈕。我從未更新後的佈局參數將視圖添加到查看組,但parent.updateViewLayout(childView, updatedParams)看起來很有前途。

無論如何,在你想要的按鈕上使用setVisibility(View.GONE);它是隱藏的,其餘的視圖都按照按鈕不存在的方式佈置。 (您可以使用View.INVISIBLE隱藏查看,但意見的其餘佈局彷彿按鈕是有 - 你無法看到它。)

下面是一個未經考驗的「片段」,P

private Button set; 
private Button cancel; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    // it's typical to use underscore notation for IDs - R.id.set_delay 
    set = (Button) findViewById(R.id.setDelay); 
    cancel = (Button) findViewById(R.id.cancelDelay); 
} 

public void activateDelay(View button) { 
    set.setVisibility(View.GONE); 
    cancel.setVisibility(View.VISIBLE); 
} 

public void cancelDelay(View button) { 
    set.setVisibility(View.VISIBLE); 
    cancel.setVisibility(View.GONE); 
} 

而在你的XML,你會用「設置」按鈕可見(默認)開始,「取消」走了,既match_parent的寬度:

<LinearLayout 
    android:id="@+id/buttonsContainer" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true"> 

    <Button 
     android:id="@+id/setDelay" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     android:onClick="activateDelay" 
     android:text="Set Delay" /> 

    <Button 
     android:id="@+id/cancelDelay" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     android:visibility="gone" 
     android:onClick="cancelDelay" 
     android:text="Cancel Delay" /> 
</LinearLayout> 
+0

注意,如果你有一個理由(即使它很瘋狂:P)想要使用體重,我真的很好奇。 – ataulm

+0

我想要使用重量,因爲在線性佈局中,對象的權重爲0,另一個權重爲1,則1將填充線性佈局,0根本不會顯示。我對android很陌生,這只是一種似乎對我有用的方法。 – TiberiumFusion

+0

@TiberiumFusion公平,非常合理,我讚揚你的想法有一個不錯的想法,儘管將來如果你在問題中解釋了這個推理,它會對你(和你的回答者)有所幫助;它表明你已經考慮過這個問題,並且還會幫助其他人看看這個約束是不是必需的(就像這裏的情況一樣)。歡迎來到這裏:) – ataulm

相關問題