majid mohebbi
majid mohebbi

Reputation: 21

cannot convert from view to button error

I am trying to make a simple android project. its made up of a button that shows another activity. can you please tell me whats wrong with this

cannot convert from view to button

error in the last line?

public class Main extends Activity {

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

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

Upvotes: 0

Views: 69

Answers (2)

Abdul Rahman Majeed
Abdul Rahman Majeed

Reputation: 1135

Every widget from palette is view and need to cast depend on Object behavior

in your scene you need to cast as above @Fast Snail mentioned !

in addition you should use beauty of code like

public class Main extends Activity {

Button b;

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

    init();
}

//place all initialized objects
private void init()
{
     b =  (Button) findViewById(R.id.button1);
}

}

Upvotes: 0

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9872

you have to cast view to a button

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

Upvotes: 4

Related Questions