从片段转到主要活动

时间:2018-01-17 20:53:22

标签: android-studio android-fragments android-activity

我实现了导航抽屉并使用了碎片。现在我可以从抽屉菜单切换到片段。但当我按下时,我的应用程序从该片段关闭,不知道如何返回主要活动。

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    displaySelectedScreen(id);

    return true;
}

private void displaySelectedScreen(int id) {
    Fragment frag = null;

    switch (id) {
        case R.id.trigger:
            break;
        case R.id.setup:
            if (android.os.Build.VERSION.SDK_INT >= 21) {
                getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
            }
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
            frag = new SettingsF();
            break;
        case R.id.recordings:
            if (android.os.Build.VERSION.SDK_INT >= 21) {
                getWindow().setStatusBarColor(Color.parseColor("#4E342E"));
            }
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8D6E63")));
            break;
        case R.id.howto:
            if (android.os.Build.VERSION.SDK_INT >= 21) {
                getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
            }
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
            break;
        case R.id.about:
            if (android.os.Build.VERSION.SDK_INT >= 21) {
                getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
            }
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
            break;
        case R.id.email_us:
            if (android.os.Build.VERSION.SDK_INT >= 21) {
                getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
            }
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
            break;
    }
    if (frag != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, frag);
        ft.addToBackStack(ft.getClass().getSimpleName()).commit();
    }
    DrawerLayout drawer = findViewById(R.id.drawer);
    drawer.closeDrawer(GravityCompat.START);
}

这里只是设置片段:

public class SettingsF extends ListFragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
    String[] datasource = {"Trusted Contacts", "Custom Text Set-Up"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.txtitems, datasource);
    setListAdapter(adapter);
    setRetainInstance(true);

    return rootView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("Context Set-Up");
}

public void onListItemClick(ListView l, View view, int position, long id) {
    ViewGroup viewGroup = (ViewGroup) view;
    TextView tv = (TextView) viewGroup.findViewById(R.id.txtitems);
    Toast.makeText(getActivity(), tv.getText().toString(), Toast.LENGTH_LONG).show();
}

@Override
public void onResume() {
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener( new View.OnKeyListener()
    {
        @Override
        public boolean onKey( View v, int keyCode, KeyEvent event )
        {
            if( keyCode == KeyEvent.KEYCODE_BACK )
            {
                //Already Used Intent, doesn't work
                return true;
            }
            return false;
        }
    } );
    super.onResume();
}

}

我更新了这个问题。我已经使用了addToBackStack(),然后覆盖了onResume()方法,但是当按下后退按钮时应用终止。 我真的很陌生,所以不要误解我在整个代码中实施了什么。 在此先感谢

2 个答案:

答案 0 :(得分:0)

ft.replace()之后添加此行:

ft.addToBackStack(null);

这一行将使您每次从导航栏中选择一个项目时,都会建立片段历史记录。然后当您按下后退按钮时,您将返回历史记录。如果您没有历史记录项,则该应用将关闭。

更复杂的实现可能使用名称参数(如“FragA”或“FragB”)而不是null作为addToBackStack()的参数,然后检查您的片段是否已存在于后面的堆栈而不是总是打开一个新的。这样,如果你去了A-> B-> A-> B-> A-> B,那么你在历史上就不会有三份A副本和两份B副本。

答案 1 :(得分:0)

用于硬件按钮 在片段

中的onResume方法中添加此代码
//You need to add the following line
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
          //here use intent to call mainActivity 
            return true;
        }
        return false;
}
} );

希望这会对你有所帮助