简体   繁体   中英

Error on Button keyword in Android

Maybe it sounds silly, but I am getting an error on Button keyword (where it should not be). I am a newbie, and looked almost everywhere. And everyone says that

Button b = findViewById(R.id.button1);

is correct.

My code:

package com.example.myfirstappnew;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = findViewById(R.id.button1);
    }


    @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;
    }


}

Here is the screenshot: http://pbrd.co/ZEsSw7

From what I see, you have an error because findViewById returns View and not Button , and you need to cast it to Button .

You need to cast the Button to a Button :

Button b = (Button) findViewById(R.id.button1);

And add this import:

import android.widget.Button;

Next time, when you say you have an error please include it :)

findViewById returns View, you need to cast it into Button.

Button b = (Button) findViewById(R.id.button1);

Edit:

Click on the first link that show i mport import Button(android.widget.)

or simply press ctrl+shift+o

该代码需要导入Button (如屏幕快照顶部提示中所建议)。

First you need to change

Button b = findViewById(R.id.button1);

to

Button b = (Button) findViewById(R.id.button1);

You also need to add

import java.widget.Button;

to your import statements at the top of your file. If you are using Eclipse, you should use it's "organize imports" feature (or whatever Eclipse calls it) to do this automagically for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM