[英]Different behavior of android.app.Fragment and android.support.v4.app.Fragment while using backstack
I've created Activity and added a fragment to it using FragmentManeger
. 我创建了Activity并使用
FragmentManeger
向其中添加了一个片段。 When i use android.app.Fragment
and press the back button my application closes. 当我使用
android.app.Fragment
并按返回按钮时,我的应用程序关闭。 When i use android.support.v4.app.Fragment
and press the back button, the fragment is removed from the activity, but application is still working. 当我使用
android.support.v4.app.Fragment
并按返回按钮时,该片段将从活动中删除,但应用程序仍在工作。 I can't really understand why is that happening. 我真的不明白为什么会这样。
Here is the code i used: 这是我使用的代码:
Activity: 活动:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(R.id.content_fragment, new Fragment1())
.addToBackStack("first")
.commit();
}
}
Fragment: 分段:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
When i simply replace import in Activity
and Fragment
to same classes, but in the support library, the result is different... 当我只是将
Activity
和Fragment
import替换为相同的类,但是在支持库中时,结果是不同的...
EDIT: I also replaced getFragemetManeger()
to getSupportFragmentMeneger()
and it still works different 编辑:我也将
getFragemetManeger()
替换为getSupportFragmentMeneger()
,但它仍然可以工作
if you're only looking to change the back behavior, you can try overriding onBackPressed with something like: 如果您只想更改后退行为,则可以尝试使用类似以下方法覆盖onBackPressed:
if(backstackCount() > 0)
{
super.onBackPressed
}
The issue occured because i used android.support.v7.app.AppCompatActivity and android.app.Fragment. 发生此问题是因为我使用了android.support.v7.app.AppCompatActivity和android.app.Fragment。 I should've used android.app.Fragment with android.app.Activity or AppCompatActivity with support fragment.
我应该将android.app.Fragment与android.app.Activity或AppCompatActivity与支持片段一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.