如何将数据更新到通过自定义视图类创建的对象,以便可以在自定义视图上绘制数据?

时间:2019-03-19 05:46:46

标签: java android android-layout android-view android-custom-view

我的应用程序需要将数据发布到自定义视图,然后根据从MainActivity发送的数据重绘该视图。 这是示例代码。 自定义视图->

public class custom_view extends View {
 private simple_line line;
 public custom_view(Context context) {
     super(context);
     line=new simple_line(0);
 }

 @Override
 protected void onDraw(Canvas canvas) {
     super.onDraw(canvas);
     line.draw_line(canvas);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
     super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     setMeasuredDimension(getMeasuredWidth(),getMeasuredHeight());
 }

 private class simple_line{
     private float x_val;
     private Paint mpaint;

     public simple_line(float val){
         x_val=val;
         mpaint=new Paint();
         mpaint.setColor(Color.RED);
         mpaint.setStyle(Paint.Style.STROKE);
         mpaint.setStrokeWidth(10);
     }

     public float getX_val() {
         return x_val;
     }

     public void setX_val(float x_val) {
         this.x_val = x_val;
         invalidate();
     }

     public void draw_line(Canvas canvas){
         Path mpath=new Path();
         mpath.moveTo(getWidth()/2+x_val,0);
         mpath.lineTo(getWidth()/2+x_val,getHeight());
         mpath.close();
         canvas.drawPath(mpath,mpaint);
     }
 }

 public void update_xval(float val){
     line.setX_val(val);
 }
}

这是主要活动->

public class MainActivity extends AppCompatActivity{
private Button button;
private custom_view myview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.mybutton);
myview=(custom_view)findViewById(R.id.myview);
myview=new custom_view(this);
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myview.update_xval(100);
        }
    });
}
}

按下按钮后我无法更新x_val。我在哪里出错了。更新x_val需要做什么?

1 个答案:

答案 0 :(得分:0)

draw_line(Canvas canvas)函数中存在问题。您没有在custom_view中调用此函数。您需要在invalidate()被叫之后draw_line(Canvas canvas)