我正在编写指南针Android应用程序 现在我遇到一个问题,我想在主XML文件中添加一个画布,后面的按钮设计让用户返回菜单
我使用addview()
尝试将画布指南针添加到main.xml中但仍然出错
错误是“mainLayout.addView(compassView)”上的NULLPOINTEREXCEPTION;“在MAIN.JAVA代码
这是我的代码
MAIN.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
compassView = new MyCompassView(this);
setContentView(compassView);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.compasslayout);
LayoutParams imageViewLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
compassView.setLayoutParams(imageViewLayoutParams);
mainLayout.addView(compassView);
MyCompassView.java
public class MyCompassView extends View {
private Paint paint;
private float position = 0;
public MyCompassView(Context context) {
super(context);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setTextSize(25);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLACK);
paint.setStrokeMiter(position);
}
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"
android:orientation="vertical"
tools:context=".Compass" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:id="@+id/compasslayout">
<Button
android:id="@+id/buttona"
android:layout_width="200dp"
android:layout_height="50dp"
android:background="@drawable/b_select" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingTop="10dp">
</LinearLayout>
</LinearLayout>
请帮助我,我已经坚持了一天,如果没有完成这项任务我就无法继续
答案 0 :(得分:1)
问题在于:
compassView = new MyCompassView(this);
setContentView(compassView);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.compasslayout);
您正在设置新的MyCompassView
作为内容视图而不是XML文件。这意味着当您致电findViewById()
时,无法找到身份R.id.compasslayout
的视图。您拨打setContentView()
的电话应为setContentView(R.layout.mylayout)
。