簡體   English   中英

如何在活動加載期間禁用EditText控件並通過用戶操作啟用它

[英]How to disable EditText control during activity load and enable it by user action

我有一個加載的活動,該活動具有多個EditText控件和一個按鈕。 EditText控件顯示來自SQLlite數據庫的值。 我希望當活動加載時EditTtext控件為只讀(甚至不可點擊),然后在用戶單擊按鈕時變為可編輯/可點擊。

我在這里閱讀了很多其他主題,看來您可以用幾種不同的方法來完成。

  1. 禁用XML控制並啟用代碼(用戶操作)
  2. 禁用代碼中的控件(onCreate)並啟用代碼中的(用戶操作)

現在,我無法工作。 好像我禁用了它,就永遠無法再次啟用它以供用戶輸入。 而且,如果啟用它,它將始終處於啟用狀態,而永遠不會禁用它。

這是我當前的代碼:

XML-這是我要在用戶執行某些操作(單擊按鈕)之前禁用的控件

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1.5"
            android:layout_height="wrap_content"
            android:cursorVisible="true"
            android:editable="false"
            android:inputType="numberDecimal"
            android:id="@+id/itemPrice"/>
    </TableRow>
    <!-- End Item Price -->

JAVA-這是僅清除表單/ UI並嘗試啟用2個EditText字段供用戶輸入的代碼

//Add item to the inventory.  Enables the EditText control for user intput (name and price)
public void addNewItem(View view)
{
    try
    {
        //Clear the fields on the form/UI
        itemId.setText("");
        itemName.setText("");
        itemPrice.setText("");
        itemDelete.setText("");

        //Enable the controls
        itemName.setEnabled(true);
        itemPrice.setEnabled(true);
        itemName.setFocusable(true);
        itemPrice.setFocusable(true);
        itemName.setClickable(true);
        itemPrice.setClickable(true);
    }
    catch(Exception erMsg)
    {
        erMsg.printStackTrace();
    }
}

即使從未禁用過每個控件,我仍然具有setEnabled(true),但是最新代碼只是嘗試進行任何操作來啟用它。

我不想讓這個問題主觀,但是如果有優先級(XML或Java),還有更好的方法嗎? 例如,如果XML將字段設置為:focusable:false,而Java將字段設置為setFocusable(true),那么是否有優先級?

您可以在加載完成后動態將android:editable設置為android:editable ="true"

我將答案放在這里,因為似乎這個問題被問了很多,而且答案從未真正理解或清楚。

這是我不使用XML的方式

在onCreate()方法中,我通過以下代碼禁用了用戶輸入:

//Disable the itemName control
        itemName.setInputType(InputType.TYPE_NULL);
        itemName.setFocusable(false);

        //Disable the itemPrice control
        itemPrice.setInputType(InputType.TYPE_NULL);
        itemPrice.setFocusable(false);

我在用戶單擊按鈕后啟用了控件,但是在按鈕的actionListener中並沒有完成,只是單擊按鈕時調用了一個方法。

//Enable the controls
            itemName.setInputType(InputType.TYPE_CLASS_TEXT);
            itemName.setFocusableInTouchMode(true);
            itemName.setFocusable(true);

        itemPrice.setInputType(InputType.TYPE_CLASS_TEXT);
        itemPrice.setFocusableInTouchMode(true);
        itemPrice.setFocusable(true);

這可以完全正常工作,並且當未啟用EditText進行編輯時,它仍然可見(當setDisabled(true)時不顯示為灰色)

暫無
暫無

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

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