首页 文章

Android:使用按钮实现自定义视图

提问于
浏览
0

我正在创建一个自定义视图,它将有一个位图,以便用户可以在其中绘制,并在底部使用一些普通的Android按钮进行用户交互 .

要调整我的位图大小(绘图区域的高度应该是50%)我压倒一切

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    this.setMeasuredDimension(widthMeasureSpec, (int)(parentHeight * 0.50));
super.onMeasure(widthMeasureSpec, (int)(parentHeight * 0.50));
}

这给了我一个例外,“java.lang.IllegalArgumentException:width和height必须> 0”

如果我设置super.onMeasure(widthMeasureSpec,heightMeasureSpec);我看不到我的按钮位于底部 .

如果我不写super.onMeasure(),一旦我释放鼠标,我看不到任何东西 .

我正在使用xml文件进行布局:

<view class="com.my.CustomView" android:id="@+id/myView"
    android:layout_width="fill_parent" android:layout_height="wrap_content"/>
<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="horizontal">
    <Button android:layout_height="wrap_content"
        android:text="B1" android:layout_width="wrap_content"/>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:text="B2"/>
</LinearLayout>

我还该怎么办?

2 回答

  • 1

    在dp中为自定义视图提供大小会更容易 . 然后,您可以在设计模式下查看布局 . 然后使用onSizeChanged找出画布的大小 .

    onMeasure通常在画布大小取决于运行时值时使用,例如游戏结果或加载项目数等 .

    这是一个有效的例子:

    @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);      
            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);     
            int parentHeight = MeasureSpec.getSize(heightMeasureSpec);      
            int newH = (int) (parentHeight / 1.5f);
            this.setMeasuredDimension(parentWidth, newH );
        }
    

    您的自定义vuew的构造函数也必须包含属性集:

    public CustomView(Context context, AttributeSet attrs) {     
        super(context, attrs); 
    }
    
  • 1

    您的 onMeasure() 不完整,还应该考虑模式( UNSPECIFIEDEXACTLYAT_MOST ) . Docs说 onMeasure() 可能会多次调用,即使是0-0尺寸的尺寸,也可以查看视图的大小 . 请参阅View,部分布局 . 没有必要致电 super.onMeasure() .

    我也没有给按钮充气(我的猜测是第一种情况),但是试试 Hierarchy Viewer ,它会帮助你理解视图的布局(因此在某些情况下你会看到图纸,有时候看不到) .

相关问题