NullPointer试图找到资源

时间:2016-09-09 20:15:17

标签: java android xml replace nullpointerexception

我正在查看此Search field

我正在尝试创建搜索栏,但每次都会出现以下错误:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.view.View com.arlib.floatingsearchview.FloatingSearchView.findViewById(int)'

这是我的XML文件search.xml:

<RelativeLayout 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:id="@+id/parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<View
    android:id="@+id/header_view"
    android:layout_width="match_parent"
    android:layout_height="@dimen/sliding_search_view_header_height"
    android:background="#01579B"/>

<FrameLayout
    android:id="@+id/dim_background"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.arlib.floatingsearchview.FloatingSearchView
        android:id="@+id/floating_search_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:translationY="@dimen/sliding_search_view_header_height"
        app:floatingSearch_close_search_on_keyboard_dismiss="false"
        app:floatingSearch_dimBackground="false"
        app:floatingSearch_dismissOnOutsideTouch="true"
        app:floatingSearch_leftActionMode="showHamburger"
        app:floatingSearch_menu="@menu/menu_search_view"
        app:floatingSearch_searchBarMarginLeft="@dimen/search_view_inset"
        app:floatingSearch_searchBarMarginRight="@dimen/search_view_inset"
        app:floatingSearch_searchBarMarginTop="@dimen/search_view_inset"
        app:floatingSearch_searchHint="Search..."
        app:floatingSearch_showSearchKey="true"
        app:floatingSearch_suggestionsListAnimDuration="250"/>
</FrameLayout>

这就是我在活动课中所做的:

public class CreateSearch extends AppCompatActivity{

FloatingSearchView mSearchView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search.xml);

    mSearchView.findViewById(R.id.floating_search_view);
 ...

我在这里收到错误

mSearchView.findViewById(R.id.floating_search_view);

任何想法为什么?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

mSearchView尚未初始化,因此默认值为null。尝试更改为

mSearchView = (FloatingSearchView) findViewById(R.id.floating_search_view);