[英]Eclipse error : button1 cannot be resolved or is not a field
這是我的MainActivity.java代碼:
package com.dg.buttontest3;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("dg","button was clicked");
}
}
這是activity_main.xml代碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="18dp"
android:text="Button" />
</LinearLayout>
在Eclipse ADT上運行此代碼時出現以下錯誤:button1無法解析或不是字段。 我不明白我的代碼有什么問題。 請幫忙。
您尚未發布XML代碼,但由於此代碼似乎正常工作:
button = (Button)findViewById(R.id.button1);
我猜想在您的activity_main.xml
您永遠不會創建一個名為button1
東西,或者您不會使用@+id/
前綴。
它看起來應該像這樣:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button1"/>
剛剛意識到其他事情,您需要更改LinearLayout
開頭標記,使其具有一個>
。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
這可能會導致按鈕無法正確識別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.