Добавление TextInputLayout динамически вызывает исключение

Я пытался добавить TextInputLayout динамически. Всякий раз, когда будет нажата RadioButton, TextInputLayout будет добавлена ​​под LinearLayout.

Но после всего этого я получаю исключение --

java.lang.IllegalArgumentException: вам необходимо использовать тему Theme.AppCompat (или потомок) с библиотекой дизайна.

Хотя приложение не падает, но код ниже точки этой ошибки не выполняется.

Я обыскал весь StackOverflow и другие веб-сайты в поисках решения, но все, что там было упомянуто, похоже, что я уже сделал это.

Вот что я пробовал до сих пор -

Основная активность:

@Override
TextInputLayout textInputLayout3;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //some code here

    ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);

    try{
        textInputLayout3 = new TextInputLayout(getApplicationContext());
        textInputLayout3.setLayoutParams(layoutParams);
        editText3 = new EditText(getApplicationContext());
        editText3.setLayoutParams(layoutParams);
        editText3.setHint("Search by Rating:");

        textInputLayout3.addView(editText3);

        radio3 = (RadioButton)findViewById(R.id.radio3);

        Layout3 = (LinearLayout) findViewById(R.id.ll3);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if(checkedId == radio1.getId()) {
                    //again some code here
                }

                if(checkedId == radio2.getId()) {
                    //again some code here
                }

                if(checkedId == radio3.getId()) {
                    Layout3.addView(textInputLayout3);
                }
            }
        });
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

Приложение(приложение) build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
}

Манифест XML:

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

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

<application
    android:allowBackup="true"
    android:icon="@drawable/learningapponeicon"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Стили XML:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

Вроде все на месте, но я все еще сталкиваюсь с этой странной проблемой.

Может ли кто-нибудь помочь мне определить, что пошло не так? Заранее спасибо!


person Saumik Bhattacharya    schedule 29.03.2016    source источник


Ответы (1)


Не используйте контекст вашего приложения для создания стилизованных представлений, поскольку стилизация не работает с этим контекстом.

новый TextInputLayout (getApplicationContext ());

вы должны использовать контекст своей деятельности

new TextInputLayout(this);
person koni    schedule 29.03.2016
comment
Ух ты! Это было так глупо. :D Это сработало как шарм! Не следует недооценивать глупые изменения. :P Большое спасибо! :) - person Saumik Bhattacharya; 30.03.2016