问题
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:
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.
来源:https://stackoverflow.com/questions/14628617/execute-the-code-inside-ondraw-only-after-the-click-in-view