【问题标题】:Error in my Java code referring to my XML button引用我的 XML 按钮的 Java 代码中的错误
【发布时间】:2014-05-26 09:33:16
【问题描述】:

当我尝试将我的 Java 链接到我的 XML 时,计算机似乎没有获取我的按钮的 XML id 这里是 java 代码:

package com.android.simple;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

int counter;
Button add;
Button sub;
TextView display;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    counter = 0;
    add = (Button) findViewById(R.layout.bAdd);
}
}

XML 代码,如你所见,按钮的 id 保存为 bAdd,所以在 java 代码中也会调用:

<RelativeLayout 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"
    tools:context="${packageName}.${activityClass}" >

     <Button
         android:layout_width="200dp"
         android:layout_height="50dp"
         android:layout_below="@+id/tvDisplay"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="149dp"
         android:text="Subtract one" 
         android:id="@+id/bSub"
         />

     <Button
         android:layout_width="200dp"
         android:layout_height="50dp"
         android:layout_alignBottom="@+id/bSub"
         android:layout_alignLeft="@+id/bSub"
         android:layout_marginBottom="67dp"
         android:text="Add one" 
         android:id="@+id/bAdd"
         />

     <TextView
         android:layout_width="100dp"
         android:layout_height="20dp"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="36dp"
         android:layout_weight="0.00"
         android:text="Your total is 0 " 
         android:id="@+id/tvDisplay"
         />

</RelativeLayout>

【问题讨论】:

  • 异常/堆栈跟踪在哪里?

标签: java android xml eclipse


【解决方案1】:

改变这个

add = (Button) findViewById(R.layout.bAdd);

add = (Button) findViewById(R.id.bAdd);

【讨论】:

    【解决方案2】:

    改变这一行

     add = (Button) findViewById(R.layout.bAdd);
    

    到这里

     add = (Button) findViewById(R.id.bAdd);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-24
      • 2017-08-11
      • 2015-07-22
      • 2013-02-23
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多