Android ListView如何获取空视图事件

时间:2016-08-11 18:21:22

标签: android listview events

我遇到了一个问题。 当用户在ListView中获得emptyView时,我需要实现回溯行为。 但我不知道该怎么做。

enter image description here

listView = (ListView) view.findViewById(R.id.ENumberList);
outputWarning = (TextView) view.findViewById(R.id.warning);
listView.setEmptyView(outputWarning);

listView.setAdapter(scAdapter);

listView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
    @Override
    public void onChildViewAdded(View view, View view1) {

    }

    @Override
    public void onChildViewRemoved(View view, View view1) {
        if (scAdapter.isEmpty())
        {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().addToBackStack(null).commit(); //error
        }
    }
});

但我有错误:

08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers E/com.ashomok.eNumbers.activities.MainFragment: Can not perform this action inside of onLoadFinished
08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers W/System.err: java.lang.IllegalStateException: Can not perform this action inside of onLoadFinished
08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers W/System.err:     at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1415)
08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers W/System.err:     at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1429)
08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers W/System.err:     at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers W/System.err:     at android.app.BackStackRecord.commit(BackStackRecord.java:663)
08-11 21:05:00.401 9289-9289/com.ashomok.eNumbers W/System.err:     at com.ashomok.eNumbers.activities.MainFragment$2.onChildViewRemoved(MainFragment.java:153)

无论如何,我的解决方案看起来很难看。你能给我更好的主意吗?

1 个答案:

答案 0 :(得分:1)

1个选项(不是elegent但应该有效):

if (emptyView.getVisibility() == View.VISIBLE) {
   onBackPressed();
}

但是您应该为用户添加延迟以阅读有关无结果的信息。

  1. 检查适配器中的列表大小。

    如果搜索后没有结果,那么onBackPressed();