2015-11-15 2 views
0

У меня есть активность, которая размещает FrameLayout, и динамически отображает пользовательские фрагменты.Почему тема Android не влияет на элементы внутри фрагмента?

Моя цель состоит в том, чтобы иметь стиль стилей style.xml, который применяется ко всем кнопкам внутри всех фрагментов.

Это мой styles.xml файл:

<!-- Base application theme. --> 
<style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar"> 
    <item name="android:buttonStyle">@style/bt</item> 
</style> 

<style name="bt" parent="@android:style/Widget.Button"> 
    <item name="android:background">#992323</item> 
</style> 

activity_login.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.example.app.LoginActivity"> 


    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/login_frame_layout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"/> 

</LinearLayout> 

и, наконец, fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     android:paddingBottom="@dimen/activity_vertical_margin" 
     tools:context="com.example.app.LoginBackupKeyFragment" 
     android:orientation="vertical"> 

    <Button 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Got it!" 
     android:id="@+id/button" 
     android:layout_gravity="center_horizontal" 
     android:onClick="BackupKeyGotItButtonClicked"/> 


</LinearLayout> 

Но стиль не применяется! Зачем?

EDIT 15.11.2015

После прочтения этого вопроса, я думаю, что я должен упомянуть, что я использую пользовательский onCreateView функцию в моем фрагменте и это выглядит следующим образом:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    // create ContextThemeWrapper from the original Activity Context with the custom theme 
    final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.AppThemeDark); 

    // clone the inflater using the ContextThemeWrapper 
    LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper); 

    View fragmentView = localInflater.inflate(R.layout.fragment_login_new, container, false); 

    pass1 = (EditText)fragmentView.findViewById(R.id.login_new_pass1); 

    return fragmentView; 
} 

EDIT 2 15,11 .2015 это мой манифест XML

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.app" > 

    <uses-permission android:name="android.permission.READ_SMS" /> 

    <application> 

     <activity android:name=".StartUpActivity" 
      android:theme="@style/AppTheme.NoActionBar" 
      android:noHistory="true"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 

       <action android:name="android.intent.action.DEFAULT" /> 
      </intent-filter> 
     </activity> 


     <activity 
      android:name=".LoginActivity" 
      android:label="@string/title_activity_login" 
      android:theme="@style/AppThemeDark" 
      android:windowSoftInputMode="adjustResize"> 
     </activity> 
    </application> 

</manifest> 

EDIT 3 !! ВАЖНО !!

Я заметил, это должно быть связано с

<item name="android:buttonStyle">@style/bt</item> 

как, например, добавлено:

<item name="colorControlNormal">#f00</item> 
<item name="colorControlActivated">#0f0</item> 
<item name="colorControlHighlight">#00f</item> 

AppThemeDark стиль работает и показывает ОК во фрагменте. только android:buttonStyle и simmilaruly, например. android.editTextStyle не работает.

+0

Пожалуйста, вашего кода manifest.xml –

+0

Я отправил манифест –

ответ

0

Может быть, слишком поздно, но если я правильно понимаю, что вы хотите установить разные colorControlNormal, colorControlActivated и colorControlHighlight, чем указано в глобальном масштабе в вашей теме и применить его только для одной кнопки.У меня была аналогичная проблема (я хотел белый цвет акцента для EditText), и я решить это нравится следующим образом:

  1. создать стиль в values/styles:

    <style name="ColorOverwrite" parent="AppTheme"> <item name="android:textColorHint">@color/white_54p</item> <item name="colorAccent">@color/colorWhite</item> <item name="colorControlNormal">@color/white_54p</item> <item name="colorControlActivated">@color/colorWhite</item> </style>

  2. добавить app:theme="@style/ColorOverwrite" (UPDATEapp:theme="..." теперь не рекомендуется, мы должны использовать android:theme="") для определенного контроля (EditText в моем случае)

    <EditText android:id="@+id/id" android:textColor="@color/colorBlueLight" android:inputType="text" app:theme="@style/ColorOverwrite" android:layout_width="match_parent" android:layout_height="wrap_content" />

  3. убедитесь, что вы сделать не набор одновременно style="@style/somestyle" для этого элемента управления или вы получите сообщение об ошибке.

Example image showing applied theme - EditText в красном прямоугольнике имеет свою собственную тему, EditText в желтом прямоугольнике показывает по умолчанию стиля цвета от темы

Смежные вопросы