后退时从片段(导航视图)转到主活动

时间:2018-01-30 12:42:01

标签: android android-fragments navigation-drawer back navigationview

试过很多方法,但都没有完美的效果。我想从导航视图中设置的片段中获取主要活动。 我试过了

@Override
public void onBackPressed() {
    startActivity(new Intent(this, MainActivity.class));
}

但它不能正常运作。我希望它就像当我在一个支离破碎的活动中它返回到main并且再次点击它退出时(我已经这样做了),当我按下后回到主要活动帮助我

MainActivity.java

public class MainActivity extends AppCompatActivity {

private static final int PERMISSION_REQUEST_CODE = 1000 ;

private static final String TAG = "MainActivity";

private AdView mAdView;

ImageView imageView;


RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;

List<Item> items;
CustomAdapter adapter;
private long backpressedtime;




@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case PERMISSION_REQUEST_CODE:
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(this,"Permission Denied", Toast.LENGTH_SHORT).show();
            }
            break;

        }
    }




private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String str="Click on Wallpaper to set  Wallpaper";
    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
    imageView=(ImageView)findViewById(R.id.imageView);
    mDrawerLayout=(DrawerLayout) findViewById(R.id.dl);
    mToggle=new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    NavigationView navigationView = (NavigationView) findViewById(R.id.Navigation_v);
    setupDrawerContent(navigationView);
    ActionBar actionBar = getSupportActionBar();

    recyclerView =(RecyclerView)findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    imageView=(ImageView)findViewById(R.id.imageView);




    initItem();






    //start service and play music
    startService(new Intent(MainActivity.this, SoundService.class));






}
public void toast(View v) {
    Toast.makeText(MainActivity.this, "Wallpaper Set", Toast.LENGTH_LONG).show();
}
private void  initItem() {

    items = new ArrayList<>();

    items.add(new Item(0,"Wide","https://images8.alphacoders.com/532/thumb-1920-532407.jpg"));
    items.add(new Item(1, "Wide","https://images5.alphacoders.com/394/thumb-1920-394511.jpg"));
    items.add(new Item(1,"Wide","https://images5.alphacoders.com/408/thumb-1920-408539.jpg"));


    adapter = new CustomAdapter(this,items);
    recyclerView.setAdapter(adapter);





}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

protected void onDestroy() {
    //stop service and stop music
    stopService(new Intent(MainActivity.this, SoundService.class));
    super.onDestroy();
}
public void selectItemDrawer(MenuItem menuItem){
    Fragment myFragment = null;
    Class fragmentClass;
    switch (menuItem.getItemId()) {

        case  R.id.walkthrough:
            fragmentClass = Walkthrough.class;
            break;

        case R.id.info:
            fragmentClass = About.class;
            break;
        default:
            fragmentClass = Walkthrough.class;


    }
    try {
        myFragment = (Fragment) fragmentClass.newInstance();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
    setTitle(menuItem.getTitle());
    mDrawerLayout.closeDrawers();







}
private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            selectItemDrawer(item);
            return true;
        }
    });
}




@Override
public void onBackPressed() {


    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Are you sure you want to exit?");
    builder.setCancelable(true);
    builder.setNegativeButton("No Stay ;-)", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    builder.setPositiveButton("Yes :'-(", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();

}

Walkthrough.java

public class Walkthrough extends Fragment {


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public Walkthrough() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment Walkthrough.
 */
// TODO: Rename and change types and number of parameters
public static Walkthrough newInstance(String param1, String param2) {
    Walkthrough fragment = new Walkthrough();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment


    View v = inflater.inflate(R.layout.fragment_walkthrough, container, false);

    WebView webView = (WebView)v.findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true); //enable javascript
    webView.setWebViewClient(new WebViewClient());    //important to open url in your app
    webView.loadUrl("http://ign.com/wikis/the-last-of-us/Prologue");
    return v;



}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

2 个答案:

答案 0 :(得分:3)

如果您想返回 MainActivity onBack点击 WalkthroughFragment ,那么在提交您的片段时,请使用以下方法将其添加到 BackStack

FragmentTransaction addToBackStack (String name)

此方法将执行以下操作:

将此事务添加到后台堆栈。这意味着事务将在提交后被记住,并在稍后从堆栈中弹出时将反转其操作。

你可以像那样使用它

FragmentTransaction ftx = getFragmentManager().beginTransaction();
ftx.replace(R.id.my_container_frame, fragment);
ftx.addToBackStack(null);
ftx.commit();

答案 1 :(得分:0)

或者,您将所有函数调用都包含在一行中

 getSupportFragmentManager().beginTransaction().replace('Your Fragment Container ID', new 'Fragment Class Name').addToBackStack(null).commit();

干杯!

相关问题