2014-10-26 43 views
0

我是Android的新手,我有這個問題:形狀drawable不能應用於TextView。 我TextView的Java代碼如下:爲什麼形狀不能適用於android中的textview

shape = getResources().getDrawable(R.drawable.shape_tag_round_corner); 
this.setBackgroundDrawable(shape); 
this.setBackgroundColor(color); 
this.setText(roleName); 
this.setGravity(Gravity.CENTER); 

XML形狀:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<corners android:radius="5dp"></corners> 
<padding 
    android:left="5dp" 
    android:top="0dp" 
    android:right="5dp" 
    android:bottom="0dp" 
/> 
</shape> 

最後,TextView中沒有得到在代碼中設置好的形狀和顏色,爲什麼呢?

回答

0

您只能有一個可繪製的背景。

首先你設置形狀(這是透明的),然後用顏色替換它。

如果你想有一個花形,使用XML:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 

    <solid android:color="#ffffff" /> 

    <corners android:radius="5dp"></corners> 
    <padding 
    android:left="5dp" 
    android:top="0dp" 
    android:right="5dp" 
    android:bottom="0dp" 
/> 
</shape> 

然後:

shape = getResources().getDrawable(R.drawable.shape_tag_round_corner); 
shape.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.DST_ATOP)); 
this.setBackgroundDrawable(shape); 
+0

這是正確的,其實我想每次都改變顏色,所以如何使它,謝謝。 – liaoheng 2014-10-26 15:10:04

+0

我已經更新了我的答案。 (你仍然需要指定一個顏色,而不是透明的形狀) – 2014-10-26 15:20:02

+0

我已經嘗試了幾次不同類型的PorterDuff.Mode,但它沒有起作用。顏色總是被忽略。最終,我使用不同的xml文件來實現感謝您提供這些建議並幫助我改進編輯,您真是太棒了! – liaoheng 2014-10-26 15:55:58

0

您可以在Android的textviews形狀,去你的XML文件,並查找代碼 INTIAL行,他們將是這個樣子

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".ScreenOnOff" > 

這裏再lative佈局是一種可繪製的視圖,並且在xml文件中嘗試重力而不是通過java。您的可繪製問題將在xml本身中解決。希望這是一些幫助

相關問題