Android: How to load correctly ViewStub in library

醉酒当歌 提交于 2019-12-11 12:17:01

问题


I created a library that uses ViewStub and integrated it to my project. When I run the application I get java.lang.IllegalArgumentException: ViewStub must have a valid layoutResource and just after Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference.

I created another project without that library but the exact same viewstub and it worked.

So I guess the library loads the ViewStub slower the the application. Correct me if I'm wrong.

Is there any approach/solution to load the ViewStub from the library ?


回答1:


So I want to answer to my question to any one will face this problem in the future.

I just replaced the tag <ViewStub> by <include> and added the layout to it like this

<include
    android:id="@+id/include_action_bar"
    android:layout_width="fill_parent"
    android:layout_height="59dp"
    layout="@layout/actionbar_layout_sml" />

and then I setup the visibility depending of my needs like this (for example to the actionBar):

public void setActionBarVisibility(boolean visible) {
    View view = findViewById(R.id.include_action_bar);
    if (view != null) {
        if (visible) {
            view.setVisibility(View.VISIBLE);
        }
        else {
            view.setVisibility(View.GONE);
        }
    }
}

Hope this will help someone, somewhere.



来源:https://stackoverflow.com/questions/51671920/android-how-to-load-correctly-viewstub-in-library

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