【问题标题】:Android customview ondraw variableAndroid customview ondraw 变量
【发布时间】:2015-02-17 18:55:36
【问题描述】:

我有一个自定义视图,我在其中显示两个矩形。我想通过我从 mainactivity 发送的变量来设置高度。

我的 customview 类如下。

package com.example.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {
    Paint paint;
    Paint paint2;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint2 = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        paint.setColor(Color.RED);
        paint2.setColor(Color.DKGRAY);
        canvas.drawRect(150, 0, 200, 100, paint);
        canvas.drawRect(200, 0, 250, 150, paint2);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(400, 300); 
    }

}

而且主类是标准的

package com.example.customview;


import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

如何从 oncreate 或 onstart 更改高度。

感谢大家的帮助。

【问题讨论】:

    标签: java android variables ondraw custom-view


    【解决方案1】:

    您需要创建一个变量并从 Activity 设置它。例如:

    private int mHeight = 0;
    
     @Override
    protected void onDraw(Canvas canvas) {
    
        paint.setColor(Color.RED);
        paint2.setColor(Color.DKGRAY);
        canvas.drawRect(150, 0, 200, 150 + mHeight, paint);
        canvas.drawRect(200, 0, 250, 200 + mHeight, paint2);
    }
    
    public void setRectHeight(final int height) {
        mHeight = height;
        invalidate();
    }
    

    并在您的活动中设置高度:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        MyView view = (MyView)findViewById(R.id.my_view);
        view.setHeight(50);
    }
    

    【讨论】:

      【解决方案2】:

      您需要从主要活动发送数据并从 MyView 接收数据。当您创建从主要用途打开新活动的意图时

      _YourIntent_.putExtra(_tag_,_yourData_);
      startActivityForResult(_YourIntent_, result);
      
      //put extra is simply for sending data, and to receive it the other hand , oncreate use this;
      
      Intent x = getIntent();``
      //now get the data
      int _yourvariable_ = x.getExtras().getString(_tag_).toint;
      

      【讨论】:

        猜你喜欢
        • 2014-10-16
        • 1970-01-01
        • 2020-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多