我在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? 感谢
CustomView类
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
答案 0 :(得分:0)
您正在扩展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);
}
}
顺便说一句,你只需要第一个构造函数