I have two buttons in a fragment that I want when clicking on the first button this button change to white color and the second button change to black and if click on the second button, second button change to white color and firs button change to black color this is my code in mainActivity:
public void buttonOne(View view) {
Button1 = findViewById(R.id.tg_btn2);
Button2 = findViewById(R.id.tg_btn1);
//If the Button is off
if (!btnOneOn) {
Button2.setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900));
Button1.setBackgroundColor(getResources().getColor((R.color.md_white_1000)));
Button1.setTextColor(getResources().getColor(R.color.md_blue_grey_100));
Button2.setTextColor(getResources().getColor(R.color.md_black_1000));
btnTwoOn = false;
btnOneOn = true;
Log.i("Salam",btnOneOn.toString());
}
//If it is is clicked while on
else {
btnTwoOn = false;
Button2.setBackgroundColor(getResources().getColor((R.color.md_blue_grey_900)));
}
}
public void buttonTwo(View view) {
Button2 = findViewById(R.id.tg_btn2);
Button1 = findViewById(R.id.tg_btn1);
//If the Button is off
if (!btnTwoOn) {
Button1.setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900));
Button2.setBackgroundColor(getResources().getColor((R.color.md_white_1000)));
btnOneOn = false;
btnTwoOn = true;
}
//If it is is clicked while on
else {
btnOneOn = false;
Button1.setBackgroundColor(getResources().getColor((R.color.md_blue_grey_900)));
}
but it doesn't work correctly what is your suggestion?
This is the solution Activity :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main2, container, false);
final Button button1 = v.findViewById(R.id.button);
final Button button2 = v.findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
button1.setBackgroundResource(R.color.gray);
button2.setBackgroundResource(R.color.black);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
button1.setBackgroundResource(R.color.black);
button2.setBackgroundResource(R.color.gray);
}
});
return v;
}
activity_main2.xml :
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:background="@color/black"
android:textColor="@color/white" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:background="@color/black"
android:textColor="@color/white" />