【问题标题】:Eclipse error : button1 cannot be resolved or is not a fieldEclipse 错误:button1 无法解析或不是字段
【发布时间】:2015-10-28 05:49:01
【问题描述】:

这是我的 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 无法解析或不是字段。 我不明白我的代码有什么问题。请帮忙。

【问题讨论】:

  • 把你的activity_main .xml 代码放在这里
  • 你清理并重建你的项目了吗?
  • @StefanBeike 是的,我已经清理并重建了我的项目,但结果是一样的。
  • @sanatshukla ,现在看看吧。
  • 线性布局 ">" 在您的 xml 中不可用

标签: java android eclipse


【解决方案1】:

您尚未发布您的 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 开始标签,使其具有&gt;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

这可能会导致按钮永远无法正确识别。

【讨论】:

  • 我的xml代码已经贴出来了,可以看看吗?
  • 如果您仍在从事主要活动(即刚刚开始),您可以考虑从头开始一个新项目,看看是否能解决问题。编辑:可能已经找到它
猜你喜欢
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 2012-10-24
  • 2022-01-09
相关资源
最近更新 更多