I have read through some posts on here regarding activity-fragment communication but my problem is unique; i will try state it as clear as possible for you to understand. In my app there is a Mainactivity and 2 fragments(we call these fragment1 and fragment2) which are in sliding tab layout. The main activity contains a navigation drawer, and fragment1 contains a TextView and other fragment2 contains EditText. Heres problem now, there option on drawer called share:- when it is clicked, i want to access string value in Textview of Fragment1 or value in EditText of Fragment2; depends on which fragment is active in tablayout. now i want to pass string value to text message argument of intent in order for it to be shared with whatever client the user chooses.
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_share) {
//Inside the onNavigationItemSelected
String value = " ";
Fragment currentFragment= getActiveFragment();
if(currentFragment instanceof SpeechToText){
value = ((SpeechToText)currentFragment).getText1();
}else if(currentFragment instanceof TTS){
//This one has the edittext
value = ((TTS)currentFragment).getText2();
}
//Then create the intent
//Intent shareIntent ...
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,value);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Message");
startActivity(Intent.createChooser(shareIntent, "Share via"));
}
I have this function from the post you provided to return current active fragment in tab layout.
public Fragment getActiveFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
} String tag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(tag);
}
I have implementation for methodForGettingTextViewValue() in SpeechToText fragment which is Fragment1: public String getText1() { return resultTEXT.getText().toString(); }
I have implementation for methodForGettingEditTextValue() in TTS fragment which is Fragment2 public String getText2() { return return editText.getText().toString(); }