Reputation: 6207
I am very new to Android development, so I appologise in advance if this is a "noobish" question.
Using a RelativeLayout, I have a ToggleButton with an ID of reminderToggle
:
<ToggleButton
android:id="@+id/reminderToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/reminderDesc"
android:layout_alignBottom="@+id/reminderDesc"
android:layout_toRightOf="@+id/imageView1"
android:text="ToggleButton" />
I am using:
ToggleButton reminderToggle = (ToggleButton)findViewById(R.id.reminderToggle);
then later:
if(reminderToggle.isChecked()) {
inside a button onClick
listener, inside of onCreate
, to see of the ToggleButton is checked. This was all working fine. I don't know what I did, but now the app crashes when the button is clicked. In LogCat`, I can see
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ToggleButton
at nz.co.kwiius.park.ParkActivity$4.onClick(ParkActivity.java:139)
Line 139 is:
ToggleButton reminderToggle = (ToggleButton)findViewById(R.id.reminderToggle);
As you can see in the XML, reminderToggle is a ToggleButton. So what's all this fuss about? :)
Thanks in advance, JJ56
PS: There is only one thing with id of reminderToggle, which is this ToggleButton
Upvotes: 1
Views: 1853
Reputation: 53657
If you have defined a TextView prior to ToggleButton and both are defined with same id then in that case if you try to get the togglebutton tou wil get class cast exception because findViewById() will return you the first element defined using the same id in that xml. In the following XML the first element defined with id reminderToggle is TextView. SO you can't get ToggleButton using that id
ToggleButton reminderToggle = (ToggleButton)findViewById(R.id.reminderToggle);// will result you classcast exception for the following xml
XML
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:id="@+id/reminderToggle" />"
<ToggleButton
android:id="@+id/reminderToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
Upvotes: 0
Reputation: 1835
Clean and rebuild it dude. Also make sure you check build automatically always to avoid such problems.
Upvotes: 7