【问题标题】:adding canvas into a LinearLayout将画布添加到 LinearLayout
【发布时间】:2013-01-31 17:31:25
【问题描述】:

我正在编写一个指南针安卓应用程序 现在我面临一个问题,我想在主 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>

请帮帮我,我已经坚持了一天,如果没有完成这项任务,我将无法继续

【问题讨论】:

    标签: android canvas android-linearlayout compass-geolocation


    【解决方案1】:

    问题出在这里:

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

    您正在将新的MyCompassView 设置为内容视图,而不是您的 XML 文件。这意味着当你调用findViewById()时,找不到id为R.id.compasslayout的View。您对setContentView() 的呼叫应为setContentView(R.layout.mylayout)

    【讨论】:

    • 我已经改变了你所说的 setContentView(R.layout.mylayout) 但它在 mainLayout.addView(compassView); 上仍然是 NULLPOINTER;这个应用程序的原始布局文件是 R.layout.compass
    猜你喜欢
    • 2016-03-18
    • 2021-11-16
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多