android - 我如何从自定义 View 中获取宽度和高度尺寸?

标签 android view draw

我有一个自定义 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);

    }
}

使用这个简单的配置文件:

<?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>

在我看来,我想动态地设置矩形的宽度...

我试过了:

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

//抛出 nullPointerException 因为 parent 为 null ...

还有:

          getRootView().getWidth();

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

我该怎么做?

问候

安东尼奥·穆塞拉

最佳答案

通过将此方法添加到您的自定义 View 类:

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

关于android - 我如何从自定义 View 中获取宽度和高度尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091849/

相关文章:

php - 将数据从 Controller 传递到 Blade View laravel

windows - 如何正确定位 DBGrid 中的图标?

image - Matlab:在不同坐标上的单轴上绘制多个图像

java - Android IndexOutOfBound 异常 : Invalid location 0, 大小为 0

java - 为什么对服务对象有静态弱引用?

android - 如何在 Android Studio 2.3 中使用 Gradle 4.0

android - 如何使用 Android 通过网络流式传输摄像机流,生成有效的视频文件?

swift - 从 Collection View 执行segue

javascript - Couchdb 从文档中的两个数组发出文档

java - 绘图时如何将字符串中的字母分开