2016-11-03 13 views
2

スイッチの幅を小さくしたい。 How to change the size of a Switch WidgetHow to change Width of Android's Switch track?の現在の解決策は私の問題を解決していません。 android:switchMinWidthはminWidthを定義したばかりですが、それは2 x thumbWidthサイズよりも小さくしたいです。SwitchCompatの幅を縮小する方法は?

SwitchCompat class' onMeasure() functionに掘り下げます。幅の定義方法は次のとおりです。

// Adjust left and right padding to ensure there's enough room for the 
    // thumb's padding (when present). 
    int paddingLeft = padding.left; 
    int paddingRight = padding.right; 
    if (mThumbDrawable != null) { 
     final Rect inset = DrawableUtils.getOpticalBounds(mThumbDrawable); 
     paddingLeft = Math.max(paddingLeft, inset.left); 
     paddingRight = Math.max(paddingRight, inset.right); 
    } 

    final int switchWidth = Math.max(mSwitchMinWidth, 
      2 * mThumbWidth + paddingLeft + paddingRight); 
    final int switchHeight = Math.max(trackHeight, thumbHeight); 
    mSwitchWidth = switchWidth; 
    mSwitchHeight = switchHeight; 

私は、負のパディングを使用して検討していたが、その後、この行paddingLeft = Math.max(paddingLeft, inset.left);があります。私はinsetをどのように負の値を持っている私の親指ドロアブルに設定するかわかりません(私はinsetまたはOpticalBoundsが何であるか分かりません。別のstackoverflowの質問になるはずです)。

誰も私のSwitchCompatの幅をどのように縮小できるのか考えていますか?

更新 私はこのhttps://code.google.com/p/android/issues/detail?id=227184&thanks=227184&ts=1478485498

+0

あなたの問題を解決するためにあなた自身のトラックと親指drawableを作るでしょう。サイズを縮小する標準的な方法はありません。 – dex

+0

すでに自分の親指を描くことができます。それは、サムのドロアブルがやや大きいので問題です。しかし、私は自分のトラックの長さを2倍にしたくありません。私のトラックを持っているのは、スイッチの幅がトラックの描画可能な長さに依存していないように見えるからです。 – Elye

答えて

1

に私は挑戦がonMeasure(...)関数が呼び出された後に設定変数権利を強制的にリフレクションを使用して回避することができ、現在のアプローチをGoogleに要求を提出しました。

public class SwitchCustomWidth extends SwitchCompat { 

    //... the needing constructors goes here...  

    @Override 
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

     try { 
      Field switchWidth = SwitchCompat.class.getDeclaredField("mSwitchWidth"); 
      switchWidth.setAccessible(true); 

      // Using 120 below as example width to set 
      // We could use attr to pass in the desire width 
      switchWidth.setInt(this, 120); 

     } catch (NoSuchFieldException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

これは理想的ではありません。私は、リフレクションを必要とせずに(または、クラスを修正するためにクラス全体をコピーするか、幅問題のためにカスタムスイッチを書き直す)ことなく、他の誰かがより良い答えを寄せるようにしたいと考えています。

そこに解決策がない場合、これは他の人が同じ課題に直面するのを助けるのに今最も役立ちます。

関連する問題