当findViewById时Android返回null ListView

时间:2019-07-07 19:45:35

标签: android android-layout android-listview

我创建了一个自定义对话框(带有列表视图):

<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
    android:layout_width="332dp"
    android:layout_height="64dp"
    android:background="@android:color/black"
    android:contentDescription="@string/placeholder"
    android:scaleType="center" />
<!--android:src="@drawable/app_dialog_header" -->

<ListView
    android:id="@+id/pokemon_list_view"
    android:layout_width="match_parent"
    android:layout_height="343dp"
    android:divider="@color/colorPrimaryDark" />

</LinearLayout>

但是,当我尝试从MainActivity调用它时(使用findViewById(R.id.pokemon_list_view); )我为空:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual 
method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' 
on a null object reference

     final ArrayList<Pokemon> pokemons = databaseAccess.getAllPokemonWithTypes(type1, type2);

    // load the customized_dialog.xml layout and inflate to view
    LayoutInflater layoutinflater = getLayoutInflater();

    pokemonFoundListView = (ListView)  findViewById(R.id.pokemon_list_view);
    pokemonAdapter = new PokemonAdapter(this, pokemons);
    pokemonFoundListView.setAdapter(pokemonAdapter);

    View customizedUserView = (View) layoutinflater.inflate(R.layout.customized_dialog, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    alertDialogBuilder.setView(customizedUserView);

    AlertDialog alertDialog = alertDialogBuilder.create();

    alertDialogBuilder.setAdapter(pokemonAdapter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

        }
    });

    alertDialog.show();

但是,如果我将此ListView放在content_main.xml(MainActivty视图)中,Android会找到它。我想这里的问题是我不能从不是我的content_main.xml的另一个XML视图中引用另一个元素。

我该如何解决?

2 个答案:

答案 0 :(得分:2)

尝试在您的自定义视图上调用findViewById

    ...

    View customizedUserView = (View) layoutinflater.inflate(R.layout.customized_dialog, null);

    pokemonFoundListView = (ListView) customizedUserView.findViewById(R.id.pokemon_list_view);

    ...

希望有帮助

答案 1 :(得分:1)

您的对话框以一种惰性的方式添加到视图层次结构中。

因此,如果您尝试从活动根视图中找到列表视图(在对话框视图内部),则将找不到该列表视图。 (请考虑使用ViewStub)。

但是视图在对话框内部,因此

View customizedUserView = (View) layoutinflater.inflate(R.layout.customized_dialog, null);
pokemonFoundListView = (ListView)  customizedUserView.findViewById(R.id.pokemon_list_view);

将正确找到视图。