小编cgr*_*ene的帖子

Android:调整自定义视图的大小.父级已调整大小,但宽度/高度更改不会传递给子视图

我目前正在尝试使用Android制作基于旧学校战舰棋盘游戏的游戏.我现在只是在试图感受它以及我可能需要制作游戏的组件.

基本上我目前在布局xml文件中的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<org.greene.battleship.BoardView
    android:id="@+id/board_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true" />
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <org.greene.battleship.ShipView
            android:id="@+id/ships_view"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:clickable="true" />
    </RelativeLayout>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我希望BoardView只占用屏幕的某个部分,即视图应该是我想在此视图中创建的内容的大小.在这种情况下,它是2D板.这是通过从扩展View覆盖onMeasure()方法来完成的.视图的宽度保持不变,但高度与宽度相同,给出了完美的正方形.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){

    int parent_width = MeasureSpec.getSize(widthMeasureSpec);
    this.setMeasuredDimension(parent_width, parent_width);
    Log.d("BOARD_VIEW", "BoardView.onMeasure : width = " + this.getMeasuredWidth() + ", height = " 
            + this.getMeasuredHeight());
}
Run Code Online (Sandbox Code Playgroud)

我通过覆盖onSizeChanged()函数的视图并检查那里的值来检查视图维度是否已更改.

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
    Log.d("BOARD_VIEW", "BoardView.onSizeChanged : width = " + w + ", height …
Run Code Online (Sandbox Code Playgroud)

android parent-child dimensions custom-view

9
推荐指数
1
解决办法
5739
查看次数

标签 统计

android ×1

custom-view ×1

dimensions ×1

parent-child ×1