I'm trying to implement a toggle button an a check box in my android app like this:
In XML:
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/layout"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".Main">
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Dark Background"
android:textOff="Light Background"
android:id="@+id/toggleButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="I want pizza with"
android:id="@+id/textView"
android:layout_below="@+id/toggleButton"
android:layout_alignLeft="@+id/toggleButton"
android:layout_alignStart="@+id/toggleButton"
android:layout_marginTop="50dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cheese"
android:id="@+id/checkBox"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/toggleButton"
android:layout_alignEnd="@+id/toggleButton"
android:checked="false" />
</RelativeLayout>
In Java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.layout);
ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton);
tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
rl.setBackgroundColor(Color.BLACK);
} else {
rl.setBackgroundColor(Color.WHITE);
}
}
});
CheckBox cb = (CheckBox) findViewById(R.id.checkbox);
final TextView tv = (TextView) findViewById(R.id.textView);
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = ((CheckBox) v).isChecked();
if (checked) {
tv.setText("You want pizza with cheese");
} else {
tv.setText("Oh! I see. you don't like cheese.");
}
}
});
}
The problem is, every time I test the app it crashes and I can't find why.
So if anyone has any idea why, please help.
Aucun commentaire:
Enregistrer un commentaire