Android.widget,textView cannot be cast to android.widget,button

前端 未结 11 627
你的背包
你的背包 2020-12-08 05:01

I keep getting a runtime error when launching my activity and it says android.widget.textview cannot be cast to android.widget.button?

XML:



        
11条回答
  •  遥遥无期
    2020-12-08 05:17

    I added the logcat. But i have no idea what is happening

    This is the important information in your LogCat file:

    Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
      at com.example.intent_buttontests.PlayScreen.onCreate(PlayScreen.java:110)
    

    You read the error correctly, it is a ClassCastException. The lines below Caused by... tell you where the error was thrown, which is in PlayScreen.onCreate() on line 110. As best I can tell line 110 is:

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

    But this line is fine and the XML for btnBattle looks fine too...

    I ran your Activity with your layout myself and didn't get any errors. Have you cleaned your project? Often this will remove these "phantom" errors. (In Eclipse, Project -> Clean...)


    I do have one suggestion, you have a lot of Buttons that do similar tasks. You can do the same actions with much less code if you use the XML onClick attribute. First create a method (call it launchClick()) in your Activity like so:

    public void launchClick(View v) {
        Intent intent;
    
        switch(v.getId()) {
        case R.id.button1:
            intent = new Intent(PlayScreen.this, Inventory.class);
            break;
    
        case R.id.button2:
            intent = new Intent(PlayScreen.this, Equipment.class);
            break;
    
        // etc, etc
        }
        startActivityForResult(intent, 0);
    };
    

    And add the attribute android:onClick to every Button that you should have this behavior in play_screen.xml:

    Hope that helps!

提交回复
热议问题