简体   繁体   中英

r.id not regenerated

I am trying to create a simple button example, but when I add this code:

mButton = (Button) findViewById(R.id.button1);

it wont update my R.id file. I've tried everything including making sure automatic build is on, cleaning the project, and updating the SDK. This happens in both 1.6 and 2.2 projects.

Here's what full code is looking like:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class NewTest extends Activity {

 Button myButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myButton = (Button) findViewById(R.id.button1);
    }
}

findViewById is looking at the R.id file for the location you refer to.

Your code will not cause the file to update as it is only looking for the button.

Creating the button in your layout will cause the R.id file to update.

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Button One"/>

As you are using findViewById in context, and the view for the current context is main.xml, the above button example will need to be inside the main.xml file. Otherwise if you had another button with the same name in another .xml layout, the entry would be made in your R.id file but your code would give you a null pointer exception, because the button doesn't exist in the context you are trying to reference it from.

Make sure you have proper import for your app's R class in your Activity:

import your.app.package.R;

UPDATE: this implicit import is only needed if your Activity class is not in the root of your.app.package package.

使用R.id.something之前保存项目

I had the same problem using API 19 with the layout editor set to API 15 while trying to follow the NotePadV1 tutorial. I couldn't get the R.id.text1 to compile from the notes_row.xml file.

Originally, I had just pasted text into the xml file to generate the layout. After unsuccessfully trying deleting R and a Clean, I tried deleting the notes_row layout entirely. When I recreated the layout, I used the graphical interface to add the properties of the TextView object, just the Id @+id/text1, width and height. Then I did a Clean and compile. It worked.

由于您使用的是基于XML的布局,因此请确保main.xml文件中具有android:id属性,并以“ @ + id / button1”作为值。

It wouldn't update the generated R.java file when you just refer to an existing id.

It only updates when you add a resource. button01 must already exist in one of your .xml files, otherwise your 'findViewById(R.id.button1)' wouldn't compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM