正确实现ListView的addFooterView

Properly implement ListView's addFooterView

我一直在通过课程学习 Android 开发,我们制作了一个笔记应用程序。我完成了它,我想添加东西并改进应用程序。我尝试向 ListView 添加页脚,但我不断收到 NullPointerException:
Unable to instantiate activity ComponentInfo

这是我的代码:

  public TextView mTextView = (TextView) findViewById(R.id.footer_text); 
        final ListView listView = (ListView) findViewById(R.id.task_list);
        mTaskAdapter = new TaskAdapter(mTasks);
        listView.setAdapter(mTaskAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mLastPositionClicked = position;
//                Toast.makeText(getApplicationContext(), "Task " + (position + 1) + " was pressed", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(TaskListActivity.this, TaskActivity.class);
                Task task = (Task) parent.getAdapter().getItem(position);
                i.putExtra(TaskActivity.EXTRA, task);
                startActivityForResult(i, EDIT_TASK_REQUEST);
            }
        });
        listView.addFooterView(mTextView);

和XML:

<TextView
        android:id="@+id/footer_text"
        android:text="Works!!!"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>  

我不知道我做错了什么。另外,如果格式很奇怪,我深表歉意。这对我来说是新的。这是要点:https://gist.github.com/najubhai/dcff0ea72feea14673a8

您在 Activity 具有 window 之前调用 findViewById(),该方法应在 onCreate(Bundle) 中或之后调用。如下更改您的代码将有所帮助:

        final ListView listView = (ListView) findViewById(R.id.task_list);
        // Move the addFooterView line to here, because this method 
        // could only be called before setting the adapter with setAdapter before  KITKAT(Android 4.4)
        listView.addFooterView(LayoutInflater.from(this).inflate(R.layout.your_footer_layout, null));
        mTaskAdapter = new TaskAdapter(mTasks);
        listView.setAdapter(mTaskAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mLastPositionClicked = position;
//                Toast.makeText(getApplicationContext(), "Task " + (position + 1) + " was pressed", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(TaskListActivity.this, TaskActivity.class);
                Task task = (Task) parent.getAdapter().getItem(position);
                i.putExtra(TaskActivity.EXTRA, task);
                startActivityForResult(i, EDIT_TASK_REQUEST);
            }
        });