Android - How to create FAB programmatically?

╄→尐↘猪︶ㄣ 提交于 2019-12-19 04:12:37

问题


I have an app with full of custom views. When I try to create a FAB programmatically, it throws an error

Caused by: java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.

Here is my code.

private FloatingActionButton getFAB() {
    FloatingActionButton fab = new FloatingActionButton(getContext());
    fab.setBackgroundDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_add_white_24dp));
    return fab;
}

This is my app theme.

    <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

Please help me.


回答1:


Fixed by using theme wrapper. But still I'm surprised about using ContextThemeWrapper

private FloatingActionButton getFAB() {
    Context context = new android.support.v7.internal.view.ContextThemeWrapper(getContext(), R.style.AppTheme);
    FloatingActionButton fab = new FloatingActionButton(context);
    return fab;
}


来源:https://stackoverflow.com/questions/34555834/android-how-to-create-fab-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!