2016-10-04 58 views
0

我想使用ColorFilters更改幾個TextView元素背景的顏色。我嘗試了幾種方法來做到這一點。其中兩個是波紋管:ColorFilter不適用於TextView背景

TextView tvLeftTop, tvLeftBottom; 

tvLeftTop = (TextView) findViewById(R.id.textview_LeftTop); 
tvLeftBottom = (TextView) findViewById(R.id.textview_LeftBottom); 

float[] cmData = new float[]{ 
         1, 0, 0, 1, 0, 
         0, 1, 0, 0, 0, 
         1, 1, 1, 1, 0, 
         0, 0, 0, 1, 0}; 

ColorMatrix cm = new ColorMatrix(cmData); 
ColorFilter filter1 = new ColorMatrixColorFilter(cm); 
ColorFilter filter2 = new PorterDuffColorFilter(0x20003300, PorterDuff.Mode.LIGHTEN); 

tvLeftBottom.getBackground().setColorFilter(filter1); 
tvLeftTop.getBackground().setColorFilter(filter2); 

兩個TextView均包含在GridLayout中。這裏是.XML活動文件的相應部分:

<GridLayout 
     android:id="@+id/gridLayout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:columnCount="4" 
     android:rowCount="4" 
     android:layout_above="@+id/seekBar"> 

     <TextView 
      android:id="@+id/textview_LeftTop" 
      android:layout_columnWeight="1" 
      android:layout_rowWeight="2" 
      android:layout_rowSpan="2" 
      android:layout_row="0" 
      android:layout_column="0" 
      android:layout_marginBottom="3dp" 
      android:layout_marginRight="3dp" 
      android:layout_gravity="fill" 
      android:background="#6A77B7" 

      android:text="Title1" /> 


     <TextView 
      android:id="@+id/textview_LeftBottom" 
      android:layout_width="0dp" 
      android:layout_height="70dp" 
      android:layout_columnWeight="1" 
      android:layout_rowWeight="2" 
      android:layout_rowSpan="2" 
      android:layout_row="2" 
      android:layout_column="0" 
      android:layout_marginTop="3dp" 
      android:layout_marginRight="3dp" 
      android:layout_gravity="fill" 
      android:background="#D64F97" 

      android:text="Title2" /> 
</GridLayout> 

但有兩個目標文本的意見沒有影響(它們的顏色沒有變化)。 我做錯了什麼?

P.S.顏色的值是測試,所以有整個字符串(不是來自.xml文件的值)。我認爲現在並不重要。

+0

還有其他信息。我嘗試使用SeekBar更改TextView顏色。現在我注意到有趣的事情。我在'tvLeftTop.getBackground()。setColorFilter(filter2);'和color改變後('i'是查找欄位置的值)添加了'tvLeftTop.setText(「」+ i);''。似乎需要刷新TextView。但我不知道如何正確地做到這一點。 – Yulia

回答

0
tvLeftBottom.setBackgroundColor(Color.argb(0, 255, 255, 255)); 

你的textview沒有背景,所以你不能設置顏色。 將您的顏色設置爲背景。

+0

TextView的背景色在android:background的.xml文件中指定。但我仍然嘗試了你的建議。不幸的是,這並不奏效。 – Yulia