2011-03-19 46 views
10

有沒有辦法在Android中使EditText行爲像TextView(XML優先)? 我曾嘗試以下:禁用EditText可編輯性和焦點(如TextView)

android:editable="false" 
android:focusable="false" 
android:focusableInTouchMode="false" 
android:cursorVisible="false" 
android:longClickable="false" 

這工作,但我仍然可以觸摸EditText獲得焦點(橙色邊境),但對焦儘快刪除我的手指丟失。 我不確定focusableInTouchMode做什麼,但是當我保持接觸時它不會消除焦點。

而我不使用白色背景TextView的原因是TextView的背景很醜。 EditText的背景有圓角和陰影效果。

在此先感謝。

回答

10

EditTextTextView非常相似。我看到硬編碼爲EditText.java的唯一區別是將可編輯的默認值設置爲true,這是您手動設置的。除此之外,該EditTextstyle是:

<style name="Widget.EditText"> 
    <item name="android:focusable">true</item> 
    <item name="android:focusableInTouchMode">true</item> 
    <item name="android:clickable">true</item> 
    <item name="android:background">@android:drawable/edit_text</item> 
    <item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item> 
    <item name="android:textColor">@android:color/primary_text_light</item> 
    <item name="android:gravity">center_vertical</item> 
</style> 

TextView是:

<style name="Widget.TextView"> 
    <item name="android:textAppearance">?android:attr/textAppearanceSmall</item> 
</style> 

我的猜測是,@android:drawable/edit_text是橙色框的源。事實上,it contains

<item android:state_pressed="true" android:drawable="@drawable/textfield_pressed"/> 

最簡單的方法可能是它的背景設置爲默認的:

android:background="@android:drawable/textfield_default"

+0

感謝您的源代碼。我不確定'@ drawable/textfield_pressed'是否內置,但eclipse給我一個錯誤。在我看到你的源代碼後,我注意到我也應該關閉'android:clickable',它確實有效! – Chris 2011-03-19 02:45:46

+2

太棒了!所以答案是關閉android:可點擊?順便說一句,引用textfield_pressed的正確方法是@android:drawable/textfield_pressed – 2011-03-19 03:43:29

1

現在,我得到了新的途徑。由於我關閉了EditText的大部分功能,因此應該更好地考慮如何「美化」TextView的醜陋白色背景。答案在源代碼中: 只需將android:background="@android:drawable/edit_text"添加到TextView即可產生相同的效果。 再次感謝馬修。

3

禁用EditText可編輯性和焦點(如TextView)。

試試這個:

android:longClickable="false" 
android:clickable="false"  
android:cursorVisible="false" 
android:editable="false" 
0

您可以使用your_edit_text.setKeyListener(null);只是讓它不可編輯..

2

多少不同勢和錯誤的方法(使用 總是

myEditText.setEnabled(false); 
0

機器人: focusable =「false」 android:focusableInTouchMode =「false」

0

如果您希望EditText不可編輯或不可對焦(就像TextView),但具有正確的背景,則可以使用TextView上的屬性?editTextBackground。如果使用像@android:drawable/edit_text這樣的drawable,它將不會使用依賴於api版本的背景。

此:

<EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

具有此相同的UI屬性:

<TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="?editTextBackground"/>