单击按钮时如何更改按钮颜色

时间:2018-08-16 11:47:58

标签: java android

如何更改Button的颜色?当我单击“设备”按钮时,颜色将双向更改。然后,当我单击另一个按钮,例如“技术人员”按钮上一个按钮(“设备”)的颜色设置为默认按钮颜色,而“技术人员”按钮的颜色更改时。

here is my code

   public void onButtonTabClick(View v)
    {
        Fragment fragment = null;
        switch (v.getId())
        {
            case R.id.button_equipment:

              fragment = new EquipmentFragment();

               break;
            case R.id.button_tech:

                fragment = new TechnicianFragment();

                break;

            case R.id.button_timeline:
                fragment = new TimeLineFragment();

                break;
        }

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.show_fragment, fragment);
        transaction.commit();
    }

enter image description here

2 个答案:

答案 0 :(得分:2)

您只需要编写特定的代码来设置按钮的背景色即可。

public void onEquipmentPressed(){
    equipmentButton.setBackgroundColor(getResources().getColor(R.color.color_id));
    technicans.setBackgroundColor(getResources().getColor(R.color.default_color_id));
    timeline.setBackgroundColor(getResources().getColor(R.color.default_color_id));

}


public void onTechnicansPressed(){
    equipmentButton.setBackgroundColor(getResources().getColor(R.color.default_color_id));
    technicans.setBackgroundColor(getResources().getColor(R.color.color_id));
    timeline.setBackgroundColor(getResources().getColor(R.color.default_color_id));

}

以此类推

答案 1 :(得分:0)

您不需要像@Asset Bekbossynov一样声明许多方法来处理按钮的状态。您可以通过以下方式编写代码:

private View mLastClickView;
public void onButtonTabClick(View v)
{
    // add these code
    if (mLastClickView != null) {
        mLastClickView.setBackgroundColor(getResources().getColor(R.color.unselected));
    }
    v.setBackgroundColor(getResources().getColor(R.color.selected));
    mLastClickView = v;

    Fragment fragment = null;
    switch (v.getId())
    {
        case R.id.button_equipment:
            fragment = new EquipmentFragment();

            break;
        case R.id.button_tech:

            fragment = new TechnicianFragment();

            break;

        case R.id.button_timeline:
            fragment = new TimeLineFragment();

            break;
    }

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.show_fragment, fragment);
    transaction.commit();
}