Android SwipeRefreshLayout NULL指针异常SwipeRefreshLayout.setOnRefreshListener()

时间:2015-11-11 13:04:16

标签: android listview swiperefreshlayout

我正在尝试将pull刷新功能添加到listview中。

在fragment_page.xml中(此处定义为全局列表视图)

<LinearLayout
    style="@style/AppTheme.BaseActivity"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="xx.view.fragment.PageFragment">

    <TextView
        android:id="@android:id/empty"
        style="@style/AppTheme.WrapContent.NoResult"
        android:text="@string/no_results"/>

    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:listSelector="@drawable/list_selector"/>

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

在活动中:

public class MessageActivity extends TabBaseActivity implements ManageView, OnRefreshListener {

    private MessageController mMessageController;
    private int mSelectedTab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
        setUp(new String[]{"Unread", "Read", "Sent", "All"}, Constants.Adapter.MESSAGE_ADAPTER);
        mMessageController.loadMessages();

        //START  Swipe to refresh
        try {

            final SwipeRefreshLayout swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
            if(swipeContainer == null) {
                Logger.d("Null");
            }
            swipeContainer.setEnabled(false);
            swipeContainer.setOnRefreshListener(this);

        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
        //END  Swipe to refresh

    }

但是swipeContainer仍为null。

我尝试使用以下教程:

http://www.androidhive.info/2015/05/android-swipe-down-to-refresh-listview-tutorial/

http://www.survivingwithandroid.com/2014/05/android-swiperefreshlayout-tutorial.html

但没有运气。

我该如何解决?

非常感谢任何建议。

编辑:

视图内容在init中设置:

private void init() {
        mMessageController = MessageController.getInstance(this, getSupportFragmentManager());
        mMessageController.setView(this);
        mSelectedTab = 0;
    }

1 个答案:

答案 0 :(得分:0)

如果要在片段中使用视图(SwipeRefreshLayout等),请通过 onActivityCreated()方法初始化视图。调用 onActivityCreated()后,您就知道可以随时调用该活动了。