Android findViewById 时返回 null ListView

Android returning null ListView when findViewById

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

<?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 会找到它。我想这里的问题是我不能从另一个 XML 视图引用另一个元素,这不是我的 content_main.xml .

我该如何解决这个问题?

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

    ...

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

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

    ...

希望对您有所帮助

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

因此,如果您尝试从 activity 根视图中查找列表视图(在对话框视图中),将找不到。 (想想 ViewStub)。

但是视图在您的对话框中,因此

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

将正确找到视图。