简体   繁体   中英

Android customview ondraw variable

I have a customview where i display two rectangles. i want to set the height by a variable i sent from the mainactivity.

my customview class is the following.

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); 
    }

}

And the mainclass is standard

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);
    }
}

how can i change the height from the oncreate or onstart.

Thanks all for helping.

you need to send data from main activity and receive it from MyView. when you create the intent for opening new activity from main use

_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;

You need create a varibale and set it from Activity. For example:

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();
}

And set the height in your activity:

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM