2017-04-10 84 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; 
    } 
相關問題