gpt4 book ai didi

java - 如何使用addView添加CustomView?

转载 作者:太空宇宙 更新时间:2023-11-04 14:02:32 25 4
gpt4 key购买 nike

我在 main.java 中使用下面的代码,它可以工作!

FrameLayout view = (FrameLayout) findViewById(R.id.frame);
TextView product = new TextView(this);
product.setText("Product");
view.addView(product);

但是我想添加CustomView,不行

FrameLayout view = (FrameLayout) findViewById(R.id.frame);
CustomView v = new CustomView(this); //can't create new object
v.setImageResource(R.mipmap.scale);
view.addView(v);

如何通过addView添加CustomView?谢谢

自定义 View 类

public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CustomView(Context context) {
this(context, null);
}

public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
obtainStyledAttributes(attrs);
init();
}

attrs.xml

<resources>
<declare-styleable name="CustomView">
<attr name="src" format="reference" />
<attr name="editable" format="boolean"/>
<attr name="frameColor" format="color" />
<attr name="frameWidth" format="dimension" />
<attr name="framePadding" format="dimension" />
<attr name="degree" format="float" />
<attr name="scale" format="float" />
<attr name="controlDrawable" format="reference"/>
<attr name="controlLocation">
<enum name="left_top" value="0" />
<enum name="right_top" value="1" />
<enum name="right_bottom" value="2" />
<enum name="left_bottom" value="3" />
</attr>
</declare-styleable>
</resources>

错误日志:

03-20 23:26:11.278: E/AndroidRuntime(6706): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=0, data=null} to activity {com.smallmouth./com.smallmouth..PhotoEdit}: java.lang.NullPointerException

最佳答案

您正在扩展 View 类(或 View 类的某个子类),对吗?如果是,您需要调用 super 方法并将上下文传递给构造函数中的父级,而您没有这样做。当前版本是这样的

public class CustomView extends View {

public CustomView(Context context) {
super(context);
}

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

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}

顺便说一句,您只需要您的案例中的第一个构造函数

关于java - 如何使用addView添加CustomView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com