片段内OnBackPressed的功能

时间:2014-07-09 22:09:06

标签: android listview android-fragments fragment

正如标题所说,有人知道如何实现OnBackPressed功能,就像在Activity中一样,但在片段视图中? 当我在片段中使用onKey,onKeyDown或onBackPressed时,它不起作用 - 应用程序正在关闭。我想在按下后退按钮时执行特定代码,因为在其中一个片段中我有ListView,它根据用户操作填充数据。

因此,当按下后退时,我想修改变量的值("类别"和"部分"),用特定数据填充ListView(因此修改一些值,因为用户点击了一些东西,并刷新这个ListView),让人感觉用户会回来(从部件到类别,然后关闭应用程序)。

但正如我所提到的,当我使用onKey,onKeyDown或onBackPressed时,app正在关闭...例如当我在Fragment类中包含时:

public void onBackPressed() {
    Toast.makeText(getActivity(), "AAAA", Toast.LENGTH_LONG).show();
}

没有出现吐司。使用" onKeyDown"和" onKey" - 同样的情况......我在这里做错了什么,有什么想法吗?

4 个答案:

答案 0 :(得分:1)

回答你的第一个意见:

  

正如标题所说,有人知道如何实现OnBackPressed   功能,就像在Activity中一样,但在片段视图中?

要使后退按钮与片段一起使用,您必须将它们添加到后台堆栈中。这应该触发你想要的功能。

 // Create new fragment and transaction
 Fragment newFragment = new ExampleFragment();
 FragmentTransaction transaction = getFragmentManager().beginTransaction();

 // Replace whatever is in the fragment_container view with this fragment,
 // and add the transaction to the back stack
 transaction.replace(R.id.fragment_container, newFragment);
 transaction.addToBackStack(null);

 // Commit the transaction
 transaction.commit();

答案 1 :(得分:1)

最后,得到了它。 我不得不在我的“ActionBarActivity”中从方法“onNavigationDrawerItemSelected”将“Fragment newFragment”的声明移到此方法之外,以使其在全班中可用。然后我必须在我的“ActionBarActivity”中包含“OnBackPressed”,如下所示:

@Override
public void onBackPressed() {
    if (!newFragment.onBackPressed()) {
        super.onBackPressed();
    }
}

最后,在我的片段中,我还包括onBackPressed:

public boolean onBackPressed() {
    if (part != -1) {
        part = -1;
        toAdd = "" + category + "_";
        updateList();
        return true;
    }
    return false;
}

它的工作原理就像我想要的那样。当我向后推,当我的Fragment中的变量“part”不是-1时,它正在执行上面定义的操作,返回true为“ActionBarActivity”,因此应用程序没有关闭。但是,当我的片段中,变量为-1时,则onBackPressed应用程序将返回主视图,并且当用户推回时,应用程序正在关闭。这就是我想要的! 谢谢大家的帮助!

答案 2 :(得分:0)

//this two lines of code are still useless, i just feel sorry for them.. 
[self.navigationItem.backBarButtonItem setTarget:<#(id)#>];
[self.navigationItem.backBarButtonItem setAction:<#(SEL)#>];

答案 3 :(得分:0)

public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home:
            Intent register = new Intent(PollCreateCommunities_Activity.this, PollActivity.class);
            startActivity(register);
            return true;
    }
    return (super.onOptionsItemSelected(menuItem));
}