我怎么可以从我的customview宽度和高度尺寸? [英] how i can get width and height dimension from my customview?

查看:109
本文介绍了我怎么可以从我的customview宽度和高度尺寸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图...

i have a Custom view ...

package nan.salsa.goal.customview;

import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class DayView extends View {

    private static String TAG="DayView";

    private ShapeDrawable mDrawable;

    public DayView(Context context) {
        super(context);
    }

    public DayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DayView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void init() {

        int x = 10;
        int y = 10;
        int width = 300;
        int height = 300;

        mDrawable = new ShapeDrawable(new RectShape());
        mDrawable.getPaint().setColor(0xff74AC23);
        mDrawable.setBounds(x, y, x + width, y + height);



    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        setBackgroundColor(R.color.black);
        mDrawable.draw(canvas);

    }
}

这个简单的配置文件:

with this simple configuration file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="#E06F00">

    <nan.salsa.goal.customview.DayView android:id="@+id/dayView"
        android:layout_height="match_parent" 
        android:layout_width="fill_parent" />


</LinearLayout>

在我看来,我想我的dinamically矩形的设置宽度...

In my view i want to dinamically set width of my rectangle ...

我曾尝试:

    View parent = getParent();
     int width = parent.getWidth();  

//抛出NullPointerException,因为父母是空...

// throw nullPointerException because parent is null ...

和也:

          getRootView().getWidth();

//在这种情况下,没有空pointerException但方法返回0:

// in this case no null pointerException but method return 0:

我该怎么办?

关于

安东尼奥地涌

推荐答案

通过添加此方法您的自定义视图类:

By adding this method to your custom view class:

    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        screenW = w;
        screenH = h;
    }

这篇关于我怎么可以从我的customview宽度和高度尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆