Creating custom button class in Android

2019-07-13 00:41发布

问题:

I'm trying to create custom button class for my android app

public class TicTacButton extends Button 

I've set all the constructors inside the TicTacButton and created custom methods and properties. In my main activity, I've tried to initialize the Buttons as

TicTacButton btn = (TicTacButton) findViewById(R.id.button1);

I'm getting a

java.castClassException. android.widget.Button cannot be cast to com.example.tictactoetitan.TicTacButton

I tried changing my xml file as

<TicTacButton
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/button1"
        android:layout_toRightOf="@+id/button1" />

It didn't work.

回答1:

Using the full package name in the XML file fixed it.

<com.example.tictactoetitan.TicTacButton
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/button1"
        android:layout_toRightOf="@+id/button1" />