Mavix
Mavix

Reputation: 181

Is it safe to edit r.java in my case?

I have this line of code:

Button button = (Button) findViewById(R.id.view);

Which gives the following error:

id cannot be resolved or is not a field

That error is logical, because I have nothing what needs an Id in R.java yet, and therefore Id is missing. This will be generated when I execute the code (because I make buttons at onCreate(), and they get Id's). But Eclipse won't let me run before I fix the problem. So is it safe to add this line of code to R.java:

public static final class id {
}

Or maybe there is another sloution?

Upvotes: 0

Views: 158

Answers (4)

Paul Burke
Paul Burke

Reputation: 25584

findViewById() is used when you are referencing an XML layout that was usually set by setContentView(), or inflated with LayoutInflater.

So if you have a Button in your main.xml layout, with the id of "view", you would do the following in your Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button button = (Button) findViewById(R.id.view);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Respond to click here 
        }
    }); 
}

Upvotes: 0

Szere Dyeri
Szere Dyeri

Reputation: 15246

You cannot append R.java. But if there is anything that you want to add you can create another file of your own (like Rcustom.java), keep your stuff in it and import it wherever you use it.

Upvotes: 0

James M
James M

Reputation: 16718

If you create buttons in onCreate, they aren't added to the resources. The resources are fixed from the moment you build your APK.

Surely if you created the button, you already have the Button object and don't need to look for it in the resources anyway?

Upvotes: 1

Barry Fruitman
Barry Fruitman

Reputation: 12666

No. Anything you add to R.java will get deleted the next time you build. It is an auto-generated file.

Upvotes: 0

Related Questions