Execute the code inside onDraw() only after the cl

2019-09-09 13:43发布

I have a class that extends a view. This class is called in xml to build my view. Now the view call the onDraw automatically the onDraw function on loaded. But how i can do what is do on onDraw() function only after i click in that view?? In conclusion i need to execute the code inside onDraw() only after the click in view.

DrawView.java:

public class DrawView extends View {
    Paint mPaint = new Paint();
    Context context;

    public DrawView(Context context, AttributeSet attrs){
        super(context, attrs);
        this.context = context;
        // setWillNotDraw(true);

    }

    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        mPaint.setColor(Color.MAGENTA);
        canvas.drawRect((float) (getWidth()*0.3), (float) (getHeight()*0.3), getWidth(), getHeight(), mPaint);

main.xml:

<LinearLayout
      android:orientation="vertical"
      android:layout_height="fill_parent"
      android:layout_width="0dip"
      android:layout_weight="1">    
      <com.example.sliding.DrawView 
            android:id="@+id/tv_listRow_item1"
            android:tag="tv_listRow_item1_1"
            android:layout_height="0dip"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:width="100dip"
            android:height="30dip"
            android:background="@drawable/textview_listrow_border"/>
</LinearLayout>

main.java:

 ((DrawView)v.findViewById(R.id.tv_listRow_item1)).setOnClickListener(listener);
  private View.OnClickListener listener = new OnClickListener() {

    @Override
    public void onClick(View v) {
    }
}

Any suggestions? Thanks for your time and attention.

1条回答
老娘就宠你
2楼-- · 2019-09-09 14:11

Try overriding the

    public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// your actions here
}
}

then call invalidate() function, which will set a flag to call the onDraw() of your view.

查看更多
登录 后发表回答