简体   繁体   English

在Android的自定义视图中将大小和位置设置为imageview

[英]Set size and position to imageview in custom view in Android

I got a custom class that extends View. 我有一个扩展View的自定义类。 I want to have a imageview in this class which should be the size of the View, so when I add the View to a layout it would show the imageview for the View. 我想在此类中有一个imageview,它应该是View的大小,因此当我将View添加到布局中时,它将显示View的imageview。 My problem is, that I can't change the size of the imageview. 我的问题是,我无法更改imageview的大小。

public class CustomView extends View{

ImageView imageView;

public CustomView(Context context, float ivSize) {
    super(context);

    imageView = new ImageView(context);

    //change size of imageView here

}

What I tried: 我试过的

        LinearLayout.LayoutParams imgvwDimens = 
                new LinearLayout.LayoutParams((int)ivSize, (int)ivSize);
        imageView.setLayoutParams(imgvwDimens);

-nothing -没有

    android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
    layoutParams.width = (int)ivSize;
    layoutParams.height = (int)ivSize;
    imageView.setLayoutParams(layoutParams);

-nullpointer for layoutParams.width & layoutParams.height -用于layoutParams.width和layoutParams.height的空指针

imageView.setLayoutParams(new LayoutParams((int)ivSize, (int)ivSize));

-nothing -没有

    imageView.requestLayout();
    imageView.getLayoutParams().height = (int)ivSize;
    imageView.getLayoutParams().width = (int)ivSize;

-nullpointer for .width & .height -.nullpointer用于.width和.height

I get that there might be no params yet because I don't use a imageview from xml, but that only explains case 2 and 4. I don't get why 1 and 3 do nothing and I don't know what else I could try. 我知道可能还没有参数,因为我没有使用来自xml的imageview,但这只能说明情况2和4。我不明白为什么1和3什么也不做,我也不知道我还能做什么尝试。 What am I missing? 我想念什么?

Edit: Solution 编辑:解决方案

Works now, I extended RelativeLayout instead of View, added the imageView in the constructor like this: 现在可以工作了,我扩展了RelativeLayout而不是View,在像这样的构造函数中添加了imageView:

this.addView(imageView);  

and implemented 并实施

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    imageView.layout(0, 0, ivSize, ivSize);
}

Thanks guys! 多谢你们!

You need to make a custom ViewGroup rather than a custom view if you want it to contain another view. 如果要包含另一个视图,则需要创建一个自定义ViewGroup而不是一个自定义视图。 Typically if you do this you extend either RelativeLayout or LinearLayout, so all of the laying out code is written and you would set the appropriate type of LayoutParams. 通常,如果执行此操作,则可以扩展RelativeLayout或LinearLayout,因此将编写所有布局代码,并设置适当的LayoutParams类型。 You also have to add the ImageView to the custom ViewGroup via addView 您还必须通过addView将ImageView添加到自定义ViewGroup中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM