导航抽屉活动从片段移动到活动并返回

时间:2018-11-03 05:26:32

标签: android android-fragments android-activity android-navigation-drawer

我有一个navigation drawer activityfragments,我将把每个fragment发送到activity。如果我选择菜单的选项3是fragment,将我发送到activity时遇到问题,但是当我使用“后退”按钮返回时,它会将我发送到选项1,我将我要返回选项3。 我该如何更改? 我尝试通过parentActivity来完成此操作,但没有成功 谢谢。

我的navigation drawer activityfragments enter image description here

当我单击按钮时,它会将我发送到activityactivity中,我有一个toolbar要返回,我要返回的是选项3而不是1。

我需要在代码中做什么或可以放置什么?

enter image description here

activity

我的片段代码选项3

public class Mis_Aliados extends Fragment {

Button boton;

public Mis_Aliados() { }


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.persona_mi_perfil, container, false);

    boton=view.findViewById(R.id.buton);

    boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getActivity(), ActividadEx.class);
            startActivity(intent);
        }
    });


    return view;
}

}

我的activity代码

public class ActividadEx extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pruebaactividad);

    Toolbar toolbarback=findViewById(R.id.include);
    setSupportActionBar(toolbarback);
    getSupportActionBar().setTitle("Activity");
    ActionBar actionBar=getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);


}
}

1 个答案:

答案 0 :(得分:0)

在您的ActividadEx中添加此方法以处理工具栏的后退按钮按下

我要额外添加1个意图,以确保您要在返回导航抽屉“活动”时打开选项3

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            Intent intent = new Intent(this, NavgationDrawerActivity.class);
            intent.putExtra("openOption3", true);
            startActivity(intent); 
    }

    return super.onOptionsItemSelected(item);
}

在onCreate()内的NavigationDrawerActivty上

您可以检查Bundle是否有数据。如果其为空,则可以打开Option1片段。

如果有数据,请检查。并打开Option3片段。

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        if (bundle.getBoolean("openOption3", false)) {
            //Use Fragment Transaction to Open Option 3 Fragment
        } else {
            //Open Option 1 Fragment Or any other Fragment
        }
    } else {
        //Open Option 1 Fragment Or any other Fragment
    }

如有任何疑问,请随时发表评论。

相关问题