2016-11-29 2 views
0

は私が明示的に初期化した後、上記の宣言としてsetStyle機能を使用してスタイルを設定する必要があり除きこれは、良いですカスタムビューからスタイルattrを渡すには?

public class CustomTextSwitcher extends TextSwitcher { 
    private static final long SHOW_TEXT_ANIMATION_TIME = 100; 

    public CustomTextSwitcher(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    private void init() { 
     Animation in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); 
     Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out); 

     in.setDuration(SHOW_TEXT_ANIMATION_TIME); 
     out.setDuration(SHOW_TEXT_ANIMATION_TIME); 

     this.setInAnimation(in); 
     this.setOutAnimation(out); 
    } 

    public void setStyle(final int style) { 
     this.setFactory(new ViewSwitcher.ViewFactory() { 
      @Override 
      public View makeView() { 
       return new TextView(new ContextThemeWrapper(context, style), 
         null, 0); 
      } 
     }); 

    } 
} 

以下のようにカスタムTextSwitcherを作成しています。

私は、コンストラクタに入ったsetStyleを呼び出すが、ちょうどXMLで自分のスタイルを宣言(次のコードのように)とattr値を通じてint型の値を取得する必要があり、かつViewFacoryに沿って、それを送信しないことを願っています、すべてがinit()の機能で行われます。

<my.example.CustomTextSwitcher 
    android:id="@+id/search_list_title" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    style="@style/recentSearchHeaderText" /> 

どうすれば実現できますか?

答えて

0

私はそうする方法を見つけました。 attrs.getStyleAttribute()のように簡単です。以下のコードを表示

public class CustomTextSwitcher extends TextSwitcher { 
    private static final long SHOW_TEXT_ANIMATION_TIME = 100; 

    public CustomTextSwitcher(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(attrs); 
    } 

    private void init(AttributeSet attrs) { 

     this.setFactory(new ViewFactory() { 
      @Override 
      public View makeView() { 
       return new TextView(new ContextThemeWrapper(context, 
         attrs.getStyleAttribute()), null, 0); 
      } 
     }); 
     Animation in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); 
     Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out); 

     in.setDuration(SHOW_TEXT_ANIMATION_TIME); 
     out.setDuration(SHOW_TEXT_ANIMATION_TIME); 

     this.setInAnimation(in); 
     this.setOutAnimation(out); 
    } 
} 
0

コンストラクタから取得したAttributeSetは、XMLのstyle属性から提供される他の属性とともに生成されます。だから、それを保存してconstructor to your TextView.にそれを渡してください。 setStyleメソッドは、スタイルIDを受け入れるTextView#setTextAppearanceメソッドで実際に使用できます。 TextViewに関連付けられているスタイル属性のみが表示されます。これはAttributeSetを解析して独自のスタイルを作成するよりも簡単だと言います。

関連する問題