简体   繁体   中英

Error: incompatible types: View cannot be converted to Button

I have a problem with this code:

{
    TextView txt;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt=(TextView) findViewById(R.id.mytext);
        btn=(Button) findViewById(R.id.mybutton);

        btn.setOnClickListener (new View.OnClickListener(){
            @Override
            public void onClick(View V){
                txt.setText("TAK");
            }
        });
}

As result, I get error that says:

incompatible types: View cannot be converted to Button

What am I doing wrong?

Check your activity's xml file , mybutton should be another view component.

Your xml view button should be like this:

<Button
   android:text="Button"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:id="@+id/mybutton" />

check if is not an ImageButton or ToggleButton.

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