PopupDialog中的ListView为null

时间:2011-12-15 16:14:47

标签: java android

在我的应用程序中,我尝试在ListView内使用PopupDialog。这是在AsyncTask内完成的。我认为问题介于onPreExecuteonPostExecute之间.....所有内容都正确返回,但list = null使用findViewById()之后。我无法弄清楚为什么......注意,AsyncTask和Adapter都是内部类。

    protected void onPreExecute() {
        AlertDialog.Builder alert = new AlertDialog.Builder(CreateNewReport.this);
        LayoutInflater inflater = LayoutInflater.from(CreateNewReport.this);
        popupView = inflater.inflate(R.layout.add_expenses, null);

        alert.setTitle("Add Expenses").setView(popupView);

        alert.setNeutralButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        });

        alert.show();
    }

    protected void onPostExecute(List<Expense> expenses){
        availableExpenses = expenses;

        // create list adapter for available expenses
        ArrayAdapter<Expense> adapter = new ArrayAdapter<Expense>(CreateNewReport.this,
                android.R.layout.simple_list_item_1, expenses);

        // get a reference to the list
        final ListView list = (ListView) findViewById(R.id.listViewAvailableExpenses);

        // set the list adapter
        list.setAdapter(adapter);

        // find widgets
        final ProgressBar progress = (ProgressBar) findViewById(R.id.loading_expenses);
        final LinearLayout listLayout = (LinearLayout) findViewById(R.id.available_expenses);
        final LinearLayout progressContainer = (LinearLayout) findViewById(R.id.available_expenses_loading);

        // change visibility as needed
        progressContainer.setVisibility(View.INVISIBLE);
        progress.setVisibility(View.INVISIBLE);
        listLayout.setVisibility(View.VISIBLE);
    }

弹出框的XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ProgressBar
         android:id="@+id/loading_expenses"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         style="@android:style/Widget.ProgressBar.Large"
         android:layout_centerInParent="true"
         />
        <ListView
            android:id="@+id/listViewAvailableExpenses"
            style="@style/Container"
            android:cacheColorHint="#00000000"
            />
</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

那是因为findViewById()调用在Activity中查找你的列表(它是Activity实例的一个方法),但是你的列表在对话框中。相反,您需要保存对话框的引用,然后执行theDialog.findViewById(R.id.ListNote)

//PreExecute
theDialog = alert.create(); //theDialog is an instance variable of the asynctask
theDialog.show();


//PostExecute
final ListView list = (ListView) theDialog.findViewById(R.id.ListNote);