2013-01-31 27 views
0

我正在编程一个指南针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> 

请帮助我,我陷在这已经是一天,我不能继续没有完成这个任务

+0

'mainLayout'为null? – Howard

回答

1

的问题是在这里:

compassView = new MyCompassView(this); 
setContentView(compassView); 
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.compasslayout); 

要设置一个新的MyCompassView作为内容视图而不是您的XML文件。这意味着当您拨打findViewById()时,无法找到ID为R.id.compasslayout的视图。您拨打setContentView()应该是setContentView(R.layout.mylayout)

+0

我已经改变了setContentView(R.layout.mylayout),但是它仍然是在mainLayout.addView(compassView)上的NULLPOINTER;这个应用程序的原始布局文件是R.layout.compass –