我正在创建一个需要自定义布局的应用程序。但是在运行我的应用程序之后,简单的强制关闭。如果可能的话,任何人都可以建议原因和解决方案
提前完成
这是我的主要活动
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
这是我的自定义布局类
public class Odo extends View {
private Paint p;
private RectF rect;
public Odo(Context context) {
super(context);
Log.e("odo", "constructor");
init();
// TODO Auto-generated constructor stub
}
public void init() {
Log.e("odo", "inside init()");
rect = new RectF();
p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.GREEN);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
Log.e("odo", "inside onSizeChange");
rect.set(0, 0, w, h);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Log.e("odo", "inside onDraw");
super.onDraw(canvas);
canvas.drawRect(rect, p);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.e("odo", "inside onMeasure");
}
}
这是我的XML文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.odo.Odo
android:id="@+id/odom"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
答案 0 :(得分:1)
在自定义视图中,您需要覆盖带有AttributeSet
参数的构造函数,以便在XML布局中使用它:
只需替换
public Odo(Context context) {
super(context);
Log.e("odo", "constructor");
init();
// TODO Auto-generated constructor stub
}
通过
public Odo(Context context, AttributeSet attrs) {
super(context, attrs);
Log.e("odo", "constructor");
init();
// TODO Auto-generated constructor stub
}
答案 1 :(得分:0)
我认为你需要提供默认的构造函数,它将AttributeSet
和/或int
用于样式引用。例如:
public class Odo extends View {
private Paint p;
private RectF rect;
public Odo(Context context) {
super(context);
Log.e("odo", "constructor");
init();
// TODO Auto-generated constructor stub
}
public Odo (Context context, AttributeSet attrs) {
super(context, attrs);
Log.e("odo", "constructor");
init();
}
public Odo (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Log.e("odo", "constructor");
init();
}
public void init() {
Log.e("odo", "inside init()");
rect = new RectF();
p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.GREEN);
}
//..... and so on
}