我正在編程一個指南針android應用程序 現在我正面臨一個問題,我想在主XML文件中添加一個畫布,並使用後退按鈕設計讓用戶返回菜單將畫布添加到LinearLayout中
我用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>
請幫助我,我陷在這已經是一天,我不能繼續沒有完成這個任務
'mainLayout'爲null? – Howard