无法使用按钮

时间:2013-05-05 15:32:41

标签: java android eclipse

package com.example.one;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
Button button;
 TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addListenerOnButton();

}

public void addListenerOnButton(){

    button=(Button)findViewById(R.id.button1);//error line of code
    txt1=(TextView)findViewById(R.id.txt);//error line of code

    button.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    txt1.setText("hello");
                }
            });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);


    return true;
}

}

我已标记了行的错误代码但无法解析 .xml是

<EditText
    android:id="@+id/txt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="26dp"
    android:layout_marginTop="26dp"
    android:ems="10"
    android:inputType="text" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txt"
    android:layout_below="@+id/txt"
    android:layout_marginLeft="18dp"
    android:layout_marginTop="110dp"
    android:text="Button -MYBUT" />

我只是想在我的应用中添加一个按钮和一个textview,因为我是初学Android开发者,因此无法提前解决我的问题

4 个答案:

答案 0 :(得分:0)

  

我只是想知道关于这一行的解释

but = (Button) findViewById(R.id.but);

findViewById(Id)返回View,您必须将View强制转换为您正在使用的任何UI元素。

为了让findViewById(Id)返回一个View,你必须为每个UI元素分配一个Id(如果你想在java中使用它):

<Button
    android:id="@+id/myButtonId" 
    [...]
 />

现在你可以这样做:

but = (Button) findViewById(R.id.myButtonId);

您还应该使用onCreate()方法初始化UI元素,而不是onCreateOptionsMenu()

答案 1 :(得分:0)

在充气菜单后尝试使用findViewById。您正试图在视图中找到尚未附加到活动的元素。

答案 2 :(得分:0)

这很好,检查你的进口。在android中有两种类型的R存在。 - R由项目构建者生成 - 由Android sdk带来的R

我猜你是从android SDK导入的,不是你的项目生成的。这就是为什么eclipse会对你大吼大叫的原因。

另一种情况是,名为OnCreateOptionsMenu()回调的findViewById()方法试图到达尚未创建的视图,并返回null。

EDIT。 R的问题也可能与您的xml文件中的奇怪,不可见和难以发现的错误相关联。当您在某些xml文件中犯了大错时,构建器将返回错误并且不会生成R.但在某些情况下,构建者无法找到您的任何错误,但不会生成新的R类 - 这会导致您的R过时。

答案 3 :(得分:0)

Eclipse是一个诅咒尝试不使用它我喜欢NetBeans我喜欢NetBeans这么多为NetBeans而烦恼! 我自己的问题的答案:

 it was  a real time fault of my eclipse (a curse) not my fault. The Solution is to restart the IDE or to press the Save All from File Menu of IDE

访问:https://stackoverflow.com/a/7453201/2277645