Search code examples
androidandroid-layoutandroid-fragmentsandroid-fragmentactivity

How to add functionality in fragment java file to share button I created in home fragment?


I have added a floating share button in home_fragment.xml. But I don't know where to start on how to add functionality to that share button. Please help.

This is the code of fragment java file, I have tried do coding but I failed, I'll be glad if anyone can help.

public class HomeFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, null);
    }
}

Solution

  • public class HomeFragment extends Fragment {
                Button share_bt;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView= inflater.inflate(fragment_home, container, false);
    
            FloatingActionButton share_bt= rootView.findViewById(R.id.share_bt);
            share_bt.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
    
                    Intent myIntent = new Intent(Intent.ACTION_SEND);
                    myIntent.setType("text/plain");
                    String shareBody = "hu" ;
                    String shareSub = "mk";
                    myIntent.putExtra(Intent.EXTRA_SUBJECT,shareBody);
                    myIntent.putExtra(Intent.EXTRA_TEXT,shareSub);
                    startActivity(Intent.createChooser(myIntent, "Share Using"));
                }
            });
            return rootView;
        }
    }