Android 在程序中更改自定义视图的大小?

Android 在程序中更改自定义视图的大小?,android,android-layout,Android,Android Layout,我是android编程的初学者。我想知道我是否可以在程序中自定义自定义布局的大小 以下是我正在尝试的解决方案: 1.我创建了一个名为MyLayout的定制布局类,并将onMeasure和onScale方法编写为 MyLayout extends ViewGroup { public double childWidth, childHeight; @Override protected void onMeasure(int widthMeasureSpec, int heightMe

我是android编程的初学者。我想知道我是否可以在程序中自定义自定义布局的大小

以下是我正在尝试的解决方案: 1.我创建了一个名为MyLayout的定制布局类,并将onMeasure和onScale方法编写为

MyLayout extends ViewGroup {
  public double childWidth, childHeight;
 @Override  
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
     super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
    if (getChildCount() > 0) {  
        //In the current version, we should only have one child view 
        View childView = getChildAt(0);  
        measureChild(childView, (int)(childWidth), (int)(childHeight));  
    }  
}  

@Override  
protected void onLayout(boolean changed, int l, int t, int r, int b) {  
    if (getChildCount() > 0) {  
        View childView = getChildAt(0);  
        childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());  
    }  
}  
} 
  • 创建此布局活动的XML文件\u mylayout,在布局中,我包含一个imageview作为子布局

    <com.example.MyLayout xmlns:android="http://schemas.android.com/apk/res/android"  
       android:layout_width="match_parent"  
       android:layout_height="match_parent" >  
    
    <ImageView
          android:id="@+id/imageView1"
         android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@drawable/android" />
    
     </com.example.MyLayout>  
    

  • 现在我遇到了将MyLayout设置为null并抛出null指针异常的问题。我想我可能在很多地方做错了,但是关于MyLayout为空的原因有什么建议吗?

    我马上想到的是,onMeasure必须在退出之前调用setMeasuredDimension(int,int),否则以后调用measure将失败。即使宽度和高度测量为0,也需要这样做

    第二件事是——如果只有一个孩子,为什么会存在这种观点?你所做的只是增加开销。使用这种布局而不是直接使用子视图可能是错误的设计


    第三个问题是,您可能遇到了usl equals null情况,导致了null指针异常,但是如果不使用堆栈跟踪和xml,则无法判断异常情况。

    Hi Gabe,谢谢您的回答。我添加这个子视图是因为我想定制一个特殊大小的视图(例如,一个占整个页面3/4的图像视图),有什么方法可以做到这一点吗?我猜absolutelayout可能是答案,但我也想在程序中动态更改比例(例如,3/4到1/2)。。。我调试了代码,空指针是因为usl是空的…这不需要。使用具有布局权重的线性布局(图像视图上为3,设计的其余部分为1),将使其占据窗口的3/4。即使忽略这一点,对于如何处理元素的大小,正确的答案通常不是创建一个专门的布局来容纳它,而是从ImageView派生并在那里覆盖onMeasure。
    setContentView(R.layout.activity_mylayout);
     MyLayout usl = (MyLayout)findViewById(R.layout.mylayout);
     if(usl == null) System.out.println("SSSS");
     usl.childWidth = 200;
     usl.childHeight = 200;