如何在RecycleViewer上更改Canvas?

时间:2015-07-03 16:12:25

标签: android android-canvas android-recyclerview

我在列表项中使用带有Canvas视图的RecycleViewer。如何在RecycleViewerAdapter中更改Canvas视图的背景颜色?

下面是我的RecycleViewerAdapter中的onBindViewHolder方法

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.openprice.setText(mopenPrice.get(position));

//How can I change backgrouncolor canvas view ????

}

我的ViewHolder

public ViewHolder(View itemView) {
        super(itemView);

        openprice = (TextView) itemView.findViewById(R.id.openprice);            
        viewx = (View) itemView.findViewById(R.id.viewx);



    }

itemlist.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="@drawable/border_listfavorite"
>

<view class="com.eusecom.exforu.MyView"
      android:layout_width="fill_parent"
      android:layout_height="20dp"
      android:layout_alignParentLeft="true"
      android:id="@+id/viewx"/>

<TextView
    android:id="@+id/opentxt"
    android:text="@string/opentxt"
    android:singleLine="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/viewx"
    />

<TextView
    android:id="@+id/openprice"
    android:singleLine="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/opentxt"
    android:layout_below="@+id/viewx"
    />


</RelativeLayout>

MyView.java

public class MyView extends View {
public MyView(Context cxt, AttributeSet attrs) {
    super(cxt, attrs);
    setMinimumHeight(100);
    setMinimumWidth(100);
}

@Override
protected void onDraw(Canvas cv) {
    cv.drawColor(Color.WHITE);
    Paint p = new Paint();
    p.setColor(Color.GREEN);
    p.setStrokeWidth(5);
    cv.drawLine(20, 0, 20, cv.getHeight(), p);
}


}

1 个答案:

答案 0 :(得分:1)

使用invalidate()方法调用onDraw方法。

   @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    holder.viewx.setText(mopenPrice.get(position));

    if(condition){
          holder.viewx.setCustomColor(Color.GREEN);
          holder.viewx.invalidate();
    }

    }

公共类MyView扩展了View {

private int color = Color.WHITE;

public MyView(Context cxt, AttributeSet attrs) {
    super(cxt, attrs);
    setMinimumHeight(100);
    setMinimumWidth(100);
}

@Override
protected void onDraw(Canvas cv) {
    cv.drawColor(color);
    Paint p = new Paint();
    p.setColor(Color.GREEN);
    p.setStrokeWidth(5);
    cv.drawLine(20, 0, 20, cv.getHeight(), p);
}

public void setCustomColor(int color){
   this.color = color;
}


public ViewHolder(View itemView) {
    private MyView viewx;
    super(itemView);
    openprice = (TextView) itemView.findViewById(R.id.openprice);            
    viewx = (MyView) itemView.findViewById(R.id.viewx);

}