2017-04-10 86 views
0

在我的应用程序中,我需要能够将按钮的背景颜色更改为默认颜色。将颜色更改为自定义颜色有效,但我的用于反转该过程的代码给了我一些问题。将Android按钮重置为默认颜色和样式

我的按钮代码:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.custom_practice, container, false); 
     mNomButton = (Button) view.findViewById(R.id.custom_practice_nom_button); 
     mNomButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       mNomIsSelected = !mNomIsSelected; 
       mNomButton.setBackgroundResource(mNomIsSelected ? R.color.buttonSelected : android.R.drawable.btn_default); 
       updateView(mNomButton); 
      } 
     }); 
     return view; 
    } 

当我复位按钮资源我结束了一个镶上按钮,我不得不无边距前:

在布局充气:

enter image description here

OnClick第一次:

enter image description here

的OnClick第二时间:

enter image description here

我想避免不必创建模仿平坦按钮的自定义绘制。有没有办法获得默认的无边界按钮资源?

回答

0

当u盘背景在第二次设置由正从另一个按钮具有默认的后台背景,因此对于前比方说,在红色按钮是默认B1和按钮B2

然后代码设置背景为B1成为默认为

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) 
     b1.setBackground(b2.getBackground()); 
else b1.setBackgroundDrawable(b2.getBackground()); 
0

花了一些时间,因为许多问题的答案包括过时的代码,但我有一个解决我的问题。使用Mohamed的建议我抓住了其中一个按钮的默认Drawable值并将其存储起来。最大的问题是找到一种方法,将colors.xml中的默认颜色和我的颜色设置为与我的三元相同的类型(如果要工作)。

private Drawable mDefaultButtonColor; 
private Drawable mSelectedButtonColor; 

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     mNomButton = (Button) view.findViewById(R.id.custom_practice_nom_button); 

     mNomButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       mNomIsSelected = toggleButton(mNomButton, mNomIsSelected); 
      } 
     } 

     mDefaultButtonColor = ((Drawable) mNomButton.getBackground()); 
     mSelectedButtonColor = ContextCompat.getDrawable(getActivity(), R.color.buttonSelected); 
     return view; 
    } 


    private boolean toggleButton(Button button, boolean isSelected) { 
     isSelected = !isSelected; 
     button.setBackground(isSelected ? mSelectedButtonColor : mDefaultButtonColor); 
     return isSelected; 
    } 
相关问题