簡體   English   中英

如何以編程方式更改按鈕的重量

[英]How to change weight of a button programatically

我有一個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>

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

為什么要使用weight屬性隱藏按鈕? layout_weight用於按比例共享空間(根據給定的權重)。 我猜您可以通過將layout_weight設置為0(而將另一個的權重設置為大於0) “隱藏”按鈕。 將視圖添加到視圖組后,我從未更新過布局參數,但是parent.updateViewLayout(childView, updatedParams)看起來很有希望。

無論如何,都可以在要setVisibility(View.GONE)的按鈕上使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM