findViewById in java (R.id.bAdd)

2019-09-19 12:13发布

So i've been trying to learn android and I tried the most popular thenewbostons android tutorial, But I am stuck with the error, I'll show you MainActivity.java and Activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Your total is 0"
        android:textSize="45dp"
        android:layout_gravity="center"
        android:gravity="center" 
        android:id="@+id/tvDisplay"
        />

   <Button 
       android:layout_width="250dp" 
       android:layout_height="wrap_content"
       android:text="Add One"
       android:layout_gravity="center" 
       android:textSize="20dp"
       android:id="@id/bAdd"/>

    <Button 
       android:layout_width="250dp" 
       android:layout_height="wrap_content"
       android:text="Subtract One"
       android:layout_gravity="center" 
       android:textSize="20dp"
        android:id="@id/bSub"/>

</LinearLayout>

The Java File which is throwing the error of R.id.bAdd, Help me please?

 package com.example.addsub;

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


public class MainActivity extends Activity {

        // vars
    int counter;
    Button add,sub;
    TextView display;

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

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

标签: java android
1条回答
手持菜刀,她持情操
2楼-- · 2019-09-19 12:50

This is wrong:

android:id="@id/bAdd"/>

it should be:

android:id="@+id/bAdd"/>

same for

android:id="@+id/bSub"/>

"@+id/" means "add me to the id collection".
Otherwise, there won't be a control with that id.

"@id/" is used to reference a conttrol by another (say in a RelativeLayout)

查看更多
登录 后发表回答