Skip to main content

How to use onBackPressed and onActivityResult in fragment Android

 Hello everyone hope you are doing well .Here is another article. we all know about fragments basically A Fragment represents a reusable portion of your app's UI.

We easily use onBackPressed and onActivityResult in out Activity but we face difficulty when we use these two in our fragment class .We get no result,So if you facing same difficulty this artcile is for you.

We have to use some tricks to use these methods in our fragment.So lets start :-

First start with onActivityResult() in fragment you have to add these lines in your main Activity class

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Fragment uploadType = getSupportFragmentManager().findFragmentById(android.R.id.content);

        if (uploadType != null) {
            uploadType.onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

in findFragmentById() use can use your fragment id here ,I use android's default fargment id .

now simply add this lines in your fragment class

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends Fragment {
    

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


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

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

        ImageView myImage = (ImageView)view.findViewById(R.id.image);
        myImage.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 1);
      }
      });

        return view;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode== Activity.RESULT_OK)
        {
            if(requestCode==1)
			{
			// do your stuff here 
			}
        }
    }
}

 You got result now , Right ? .


via GIPHY

Now lets come to how we use onBackPressed functionality on fragment backPress. we all know there is no onBackPress method in fragment but we can achieve this by this code snippet.

public class MyFragment extends Fragment {
    

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


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

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

        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("TAG", "keyCode: " + keyCode);
                if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.i("TAG", "onKey Back listener is working!!!");
       // your stuff here to do onbackpress
                    return true;
                }
                return false;
            }
        });    

        return view;
    }

}

That's all guys .Thank you for your time .I you like this article then share this and also do subscribe to this blog.😐😐😐

via GIPHY



Comments

Popular posts from this blog

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone. Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :- Before this we have to add these Permissions in Manifest.xml file : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> DownloadNewVersion.java class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); bar = new ProgressDialog(getActivity()); bar.setCancelable(false); bar.setMessage("Downl...

Solution of Image not Loaded or Auto Suggestions not working in Android Studio

Sometimes we face issue when some images are not loaded or showing in Android Studio . It shows that image not loaded try to open it externally to fix format problem .It cause when some gradle files are corrupted. also if you try auto suggestions not working in xml layout files like  you can try Invalidate Caches and Restart in Android Studio's File Menu option but you will get no result . So here are some steps to follow to remove this type of problem: Step 1: Close your Android Studio Completely. Go to your User Folder - on Windows 7/8 this would be: [SYSDRIVE]:\Users[your username] (ex. C:\Users\DroidMedium\) there you find a folder with name .AndroidStudio3.5  *( i am using Android Studio 3.5.1 version your version may be different according to your Android Studio version) open this folder now you will find two folders Go to System folder  C:\Users\DroidMedium\.AndroidStudio3.5\System\ Step 2: Now under System Folder you will find Caches folder Delete the Folder Com...

How to Implement Item Click Interface in Android?

In Android development, creating interactive lists is essential to most apps. Often, these lists include items that users can click on to trigger actions such as opening a new screen or displaying more information. In this tutorial, we’ll walk through how to implement an item click interface in Android using Java and XML. By the end of this guide, you’ll know how to create a RecyclerView with an item click listener that responds to user taps. This approach is widely used in modern Android development because RecyclerView is both flexible and efficient. Step 1: Set Up Your Android Project First, create a new Android project in Android Studio. Make sure to choose Java as the programming language. Step 2: Add Dependencies Make sure that you have the required dependencies for RecyclerView in your build.gradle file. If not, add them like this: dependencies {     implementation 'androidx.recyclerview:recyclerview:1.2.1' } Sync the project after adding the dependency. Step 3: Define ...