Android: установка стиля просмотра программно



вот XML:



<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/LightStyle"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:clickable="true"
android:orientation="horizontal" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />

</RelativeLayout>


Как настроить style атрибут программно?

554   10  

10 ответов:

технически вы можете применять стили программно, с пользовательскими представлениями в любом случае:

private MyRelativeLayout extends RelativeLayout {
  public MyRelativeLayout(Context context) {
     super(context, null, R.style.LightStyle);
  }
}

конструктор одного аргумента используется при программном создании экземпляров представлений.

Так что цепочка этот конструктор к Супер, который принимает параметр стиля.

RelativeLayout someLayout = new MyRelativeLayout(context);

или как @Dori указал просто:

RelativeLayout someLayout = new RelativeLayout(context, null, R.style.LightStyle);

что сработало для меня:

Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0);
  • используйте ContextThemeWrapper

и

  • используйте конструктор 3-аргументов (не будет работать без этого)

вы не может установить стиль представления программно еще, но вы можете найти этой теме полезное.

обновление: на момент ответа на этот вопрос (середина 2012 года, уровень API 14-15) установка представления программно не была опцией (хотя были некоторые нетривиальные обходные пути), тогда как это стало возможным после более поздних выпусков API. Подробности см. в ответе @Blundell.

вы можете применить стиль к своей деятельности, выполнив:

super.setTheme( R.style.MyAppTheme );

или Android по умолчанию:

super.setTheme( android.R.style.Theme );

в вашей деятельности, перед setContentView().

для новой кнопки / TextView:

Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);

для существующего экземпляра:

mMyButton.setTextAppearance(this, R.style.button_enabled);

для изображения или макеты:

Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);

не из представленных ответов являются правильными.

вы можете установить стиль программно.

короткий ответ - взгляните на http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/Context.java#435

длинный ответ. Вот мой фрагмент кода, чтобы установить пользовательский определенный стиль программно для вашего представления:

1) Создайте стиль в ваших стилях.xml-файл

 <style name="MyStyle">
    <item name="customTextColor">#39445B</item>
    <item name="customDividerColor">#8D5AA8</item>
</style>

не забудьте определить свои пользовательские атрибуты в attrs.xml-файл

мой attrsl.xml-файл:

<declare-styleable name="CustomWidget">
    <attr name="customTextColor" format="color" />
    <attr name="customDividerColor" format="color" />
</declare-styleable>

обратите внимание, что вы можете использовать любое имя для вашего styleable (my CustomWidget)

теперь позволяет установить стиль виджета программно Вот мой простой виджет:

public class StyleableWidget extends LinearLayout {

private final StyleLoader styleLoader = new StyleLoader();

private TextView textView;
private View divider;

public StyleableWidget(Context context) {
    super(context);
    init();
}

private void init() {
    inflate(getContext(), R.layout.widget_styleable, this);
    textView = (TextView) findViewById(R.id.text_view);
    divider = findViewById(R.id.divider);
    setOrientation(VERTICAL);
}

protected void apply(StyleLoader.StyleAttrs styleAttrs) {
    textView.setTextColor(styleAttrs.textColor);
    divider.setBackgroundColor(styleAttrs.dividerColor);
}

public void setStyle(@StyleRes int style) {
    apply(styleLoader.load(getContext(), style));
}
}

макет:

<TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="22sp"
    android:layout_gravity="center"
    android:text="@string/styleble_title" />

<View
    android:id="@+id/divider"
    android:layout_width="match_parent"
    android:layout_height="1dp"/>

</merge>

и, наконец, реализация класса StyleLoader

public class StyleLoader {

public StyleLoader() {

}

public static class StyleAttrs {
    public int textColor;
    public int dividerColor;
}

public StyleAttrs load(Context context, @StyleRes int styleResId) {
    final TypedArray styledAttributes = context.obtainStyledAttributes(styleResId, R.styleable.CustomWidget);
    return load(styledAttributes);
}

@NonNull
private StyleAttrs load(TypedArray styledAttributes) {
    StyleAttrs styleAttrs = new StyleAttrs();
    try {
        styleAttrs.textColor = styledAttributes.getColor(R.styleable.CustomWidget_customTextColor, 0);
        styleAttrs.dividerColor = styledAttributes.getColor(R.styleable.CustomWidget_customDividerColor, 0);
    } finally {
        styledAttributes.recycle();
    }
    return styleAttrs;
}
}

вы можете найти полностью рабочий пример на https://github.com/Defuera/SetStylableProgramatically

Если вы хотите продолжить использовать XML (что принятый ответ не позволяет вам сделать) и установить стиль после создания представления, вы можете использовать библиотеку Paris, которая поддерживает подмножество всех доступных атрибутов.

поскольку вы раздуваете свой вид из XML, вам нужно будет указать идентификатор в макете:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_styleable_relative_layout"
    style="@style/LightStyle"
    ...

затем, когда вам нужно изменить стиль программно, после того, как макет был завышен:

// Any way to get the view instance will do
RelativeLayout myView = findViewById(R.id.my_styleable_relative_layout);

// This will apply all the supported attribute values of the style
Paris.style(myView).apply(R.style.LightStyle);

дополнительные: список поддерживаемых типов представлений и атрибутов (включает в себя фон, отступы, поля и т. д. и может быть легко продлен) и инструкции по установке с дополнительной документацией.

отказ от ответственности: я автор библиотеки.

я использовал представления, определенные в XML в моей составной ViewGroup, раздул их, добавленный в Viewgroup. Таким образом, я не могу динамически изменять стиль, но я могу сделать некоторые настройки стиля. Мой композит:

public class CalendarView extends LinearLayout {

private GridView mCalendarGrid;
private LinearLayout mActiveCalendars;

private CalendarAdapter calendarAdapter;

public CalendarView(Context context) {
    super(context);

}

public CalendarView(Context context, AttributeSet attrs) {
    super(context, attrs);

}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    init();
}

private void init() {
    mCalendarGrid = (GridView) findViewById(R.id.calendarContents);
    mCalendarGrid.setNumColumns(CalendarAdapter.NUM_COLS);

    calendarAdapter = new CalendarAdapter(getContext());
    mCalendarGrid.setAdapter(calendarAdapter);
    mActiveCalendars = (LinearLayout) findViewById(R.id.calendarFooter);
}

}

и мое представление в xml, где я могу назначить стили:

<com.mfitbs.android.calendar.CalendarView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>

<GridView
    android:id="@+id/calendarContents"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<LinearLayout
    android:id="@+id/calendarFooter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    />

Это мой простой пример, ключ ContextThemeWrapper обертка, без нее мой стиль не работает, а с помощью конструктора трех параметров представления.

ContextThemeWrapper themeContext = new ContextThemeWrapper(this, R.style.DefaultLabelStyle);
TextView tv = new TextView(themeContext, null, 0);
tv.setText("blah blah ...");
layout.addView(tv);

вы можете создать xml, содержащий макет с нужным стилем, а затем изменить фоновый ресурс вашего представления, например этой.

Comments

    Ничего не найдено.