2016-01-20 61 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 –