2017-01-23 57 views
1

我想將SwitchCompat的屬性值更改爲其他(@ style/switchColorStyleBlue)的應用程序:主題。我怎樣才能做到這一點編程? (APP:主題基本上改變了切換的顏色)Android,更改應用程序:SwitchCompat的主題值以編程方式

<android.support.v7.widget.SwitchCompat 
android:id="@+id/switch" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
app:theme="@style/switchColorStylePink"/> 

我曾嘗試這個代碼,但它沒有顯示相應的結果:

SwitchCompat switchCompat = new SwitchCompat(this); 
    switchCompat.setId(i); 
    switchCompat.setSwitchTextAppearance(getApplicationContext(), R.style.switchColorStylePink); 
    switchCompat.setChecked(false); 
    containerRelativeLayout.addView(switchCompat); 

enter image description here

我要的是改變主題(開關的顏色)從粉紅色到藍色或反之亦然。

+0

有你在運行它試圖在上面的代碼?因爲從開發者網站的文檔中,我嚴重懷疑你是否可以按照給定的方式設置主題。 見下面的摘要 引用的XML屬性部分:https://developer.android.com/reference/android/support/v7/widget/SwitchCompat.html#setSwitchTypeface(android.graphics.Typeface,%20int) 也請告訴我到底要在這個SwitchCompat –

+0

是的,我已經試過在我的問題上述代碼完成的任務。我已經更新了這個問題以獲得更多的清晰度。同時看到文檔。 –

+1

給我一些時間。我正在尋找解決方案,並會回覆您... –

回答

3

試試這個...我已經測試過,它是工作完全正常

public class MainActivity extends AppCompatActivity { 

    int[][] states = new int[][] { 
      new int[] {-android.R.attr.state_checked}, 
      new int[] {android.R.attr.state_checked}, 
    }; 

    int[] thumbColors = new int[] { 
      Color.BLACK, 
      Color.RED, 
    }; 

    int[] trackColors = new int[] { 
      Color.GREEN, 
      Color.BLUE, 
    }; 

    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch); 
     DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getThumbDrawable()), new ColorStateList(states, thumbColors)); 
     DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getTrackDrawable()), new ColorStateList(states, trackColors)); 
    } 
} 

您只需要更新「trackColors」和「thumbColor」按照您的要求/需求。

+0

@Ahmad這應該工作得很好。 –

+0

是的,絕對。感謝你們! –

相關問題