2016-01-20 62 views
1

這裏是我的代碼:如何更改背景顏色的TextView dynamicaly

繪製\ textview_rounded.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item> 
     <shape android:shape="rectangle" > 
      <corners android:radius="20dip" /> 
      <stroke android:width="1dip" android:color="#667162" /> 
     </shape> 
    </item> 
</selector> 

templatesgrid_item.xml

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

    <TextView 
     android:id="@+id/TemplateName_txt" 
     android:layout_width="match_parent" 
     android:layout_height="128dp" 
     android:layout_centerHorizontal="true" 
     android:gravity="center" 
     android:background="@drawable/textview_rounded" 
     android:text="Template"> 
    </TextView> 
</RelativeLayout> 

如何,我試圖改變顏色

Private class TemplatesAdapter extends ArrayAdapter {

public TemplatesAdapter(Context context) { 
    super(context, R.layout.templatesgrid_item, mTemplates); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    Templates vTemplate = getItem(position); 

    if (convertView == null) { 
     convertView = LayoutInflater.from(getContext()).inflate(R.layout.templatesgrid_item, null); 
    } 

    TextView vTemplateItem = (TextView) convertView.findViewById(R.id.TemplateName_txt); 
    vTemplateItem.setText(String.valueOf(vTemplate.getName())); 
    vTemplateItem.setBackgroundColor(Color.parseColor(String.format("#%06X", (0xFFFFFF & Math.abs(vTemplate.getColor()))))); 
    return convertView; 
} 

}

所以我的問題是未來,當我dynamicaly改變使用setBackgroundColor TextView的顏色(),TextView的失去形狀設置。有人可以解釋如何動態改變TextView顏色和商店的形狀設置?

回答

2

使用Drawable.setColorFilter()以色形狀:

vTemplateItem.getBackground().setColorFilter(Color.argb(255, 255, 0, 0), PorterDuff.Mode.SRC_ATOP); 
+0

你是男人!)))謝謝你,你的解決方案很簡單,工作完美。 –

0

你可以把全功能改變背景顏色?! 什麼是'某種顏色'?

請試試這個代碼來解決這個問題:

TextView mTextView = new TextView(activity); mTextView.setBackgroundResource(getResources().getColor(R.color.green)); mTextView.setText("My Text");

+0

您的解決方案也改變顏色,但形狀設置丟失。我已經添加了全功能文本,我正在閱讀數據庫中每個項目的顏色 –

0

你應該從你的觀點採取提拉,並根據所鍵入的是改變其顏色。代碼將與此類似:

Drawable background = textView.getBackground(); 
if (background instanceof ShapeDrawable) { 
    ((ShapeDrawable) background).getPaint().setColor(getResources().getColor(R.color.your_color)); 
} else if (background instanceof GradientDrawable) { 
    ((GradientDrawable) background).setColor(getResources().getColor(R.color.your_color)); 
} 
0

請問您可以嘗試下面的代碼嗎?

編輯1:

LayerDrawable bgDrawable = (LayerDrawable)mTextView.getBackground(); 
GradientDrawable shape = (GradientDrawable) bgDrawable.findDrawableByLayerId(R.id.shape_id); 
shape.setColor(Color.BLUE); 

希望這會幫助你。

+0

你好。謝謝你的回答。我已經嘗試,但趕上異常:java.lang.ClassCastException:android.graphics.drawable.StateListDrawable不能轉換爲android.graphics.drawable.GradientDrawable –