开发者

Make a simple android button

开发者 https://www.devze.com 2023-04-04 16:49 出处:网络
I am trying to make a button. I am always getting a R.id error. \"id cannot be resolved or is not a field.\"

I am trying to make a button. I am always getting a R.id error.

"id cannot be resolved or is not a field."

This line throws the error:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);

Every time i try to use something with R. it throws that same error.

If i create a field in R.java class which eclipse recommends

public static Object id;

Then, eclipse highlights .layout1

and the error said "layout1 cannot be resolved or is not a field."

Here is 开发者_开发技巧the code:

import android.widget.Button;

Button myButton = new Button(this);
myButton.setText("Press Me");

Finally add the button to the layout:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
layout.addView(myButton);

Any help is much appreciated. Is there a way to drag and drop controls? and why cant i ever use R.id?


In the XML definition of your layout, does it have the attribute “android:id="layout1"”? That’s how you give names for your widget IDs.


Your R doesn't seem to be updated or generated correctly.

R is auto generated by Eclipse if you set up your project as an Android Project. It will inspect your XMLs and generate the resource IDs for you so you could use it in your code. If you have setup your project as an Android project, try Project->Clean and see if there is any error. If there is no error during the Build, the R class with all its fields should be generated for you.

See this SO Question - Developing for Android in Eclipse: R.java not generating as well for additional help.

0

精彩评论

暂无评论...
验证码 换一张
取 消