Android onOptionsItemSelected is not functioning - android

I'm working on go-back function with my fragments. I use the action bar as return button but the function onOptionsItemSelected does not work (the function may be even not called)
This code is in my FragmentActivity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
getActionBar().setHomeButtonEnabled(false);//disable the back button
this.getFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bottom_tab);
FragmentTabHost tabHost = (FragmentTabHost)findViewById(R.id.bottom_tab_host);
tabHost.setup(this, getSupportFragmentManager(), R.id.bottom_tab_content);
//tabHost.addTab(tabHost.newTabSpec("explore").setIndicator("explore"), ListTabWidget.class, null);
tabHost.addTab(tabHost.newTabSpec("browse").setIndicator("browse"), SearchList.class, null);
}
And this code is in my Fragment(A):
public class SearchList extends Fragment implements SearchView.OnQueryTextListener{
FragmentActivity searchActivity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
searchActivity = (FragmentActivity) this.getActivity();
View searchView = inflater.inflate(R.layout.search_list, container, false);
SearchView searchBar = (SearchView)searchView.findViewById(R.id.browse_search);
searchBar.setIconifiedByDefault(false); //Showing text field in search
searchBar.setSubmitButtonEnabled(true);
searchBar.setOnQueryTextListener(this);
return searchView;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
/*Intent intent = new Intent(Intent.ACTION_SEARCH, null, searchActivity, BrowseGrid.class);
intent.putExtra(SearchManager.QUERY, query);
startActivity(intent);*/
Bundle args = new Bundle();
args.putString("search_query", query);
BrowseGrid browseFragment = new BrowseGrid();
browseFragment.setArguments(args);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.bottom_tab_content, browseFragment);
transaction.addToBackStack(null);
transaction.commit();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
}
and Fragment(B):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.grid_list, container, false);
gridView = (GridView)view.findViewById(R.id.gridView);
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
return view;
}
The aim is very simple. Pressing the back button, Fragment goes back from B to A.
Am I missing something?

As I found that the stack actually has nothing to pop(I wanna know why...), I choose an alternative to do so.
I don't know whether it is the best solution but it seems work.
replace
getFragmentManager().popBackStack();
to
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount()>0){
//Log.d("Bottom Tab", "popping backstack");
fm.popBackStack();
} else {
//Log.d("Bottom Tab", "nothing can pop");
super.onBackPressed();
}
Even the stack has nothing, it will override the onBackPressed() to go back.

How about try using the SupportFragmentManager on both Activity and Fragment(A)
currently the Fragment (A) is using
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
While in you activity onOptionsItemSelected is using
this.getFragmentManager().popBackStack();
change it to:
getSupportFragmentManager().popBackStack();

Change this line , as you are handling the FragmentTransaction from Fragment class not Activity itself. You need to get getParentFragment() first.
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
To
FragmentTransaction transaction = getActivity().getParentFragment().getFragmentManager().beginTransaction();
transaction.replace(R.id.bottom_tab_content, browseFragment);

Related

App title doesn't change after returning to previous fragment

I've been developing an android app which I included the default Navigation-Drawer from Android Studio and so on. In my home fragment, I've implemented CarViews, and then set those cardview(s) OnClickListener to replace the fragment with traditional procedure.
After the fragment replacement and new page comes, I wanted to change the Actionbar title.
So in the onCreateView(...) method, I tried,
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("B");
It worked. But after pressing the hardware back button to go back to the stacked fragment, the title remains changed & it doesn't change to "Home" again. I've tried other ways. Here's my following codes. Thanks in advance.
public class HomeFragment extends Fragment implements View.OnClickListener {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
Objects.requireNonNull(((AppCompatActivity) Objects.requireNonNull(getActivity())).getSupportActionBar()).setTitle("Home");
CardView cardView1 = root.findViewById(R.id.doctor_on);
CardView cardView2 = root.findViewById(R.id.ambulance_e);
CardView cardView3 = root.findViewById(R.id.maintainance_s);
cardView1.setOnClickListener(this);
cardView2.setOnClickListener(this);
cardView3.setOnClickListener(this);
return root;
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.doctor_on:
FragmentTransaction fragmentTransaction = Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction();
Fragment fragment1 = new doctors();
fragmentTransaction.replace(R.id.container1, fragment1).addToBackStack(getString(R.string.menu_home)).commit();
return;
case R.id.ambulance_e:
//Put Actions
FragmentTransaction fragmentTransaction2 = Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction();
Fragment fragment2 = new ambulance();
fragmentTransaction2.replace(R.id.container1, fragment2).addToBackStack(getString(R.string.menu_home)).commit();
return;
case R.id.maintainance_s:
//Put Actions
FragmentTransaction fragmentTransaction3 = Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction();
Fragment fragment3 = new maintanance();
fragmentTransaction3.replace(R.id.container1, fragment3).addToBackStack(getString(R.string.menu_home)).commit();
return;
}
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Home");
}
}
To the next fragment(where I change the titlebar and pressed back button):
public class doctors extend Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("B");
View root = inflater.inflate(R.layout.fragment_doctors, container, false);
return root;
}
}
And in the doctors Fragment... Should fix the title error.
#Override
public void onDestroyView() {
super.onDestroyView();
Objects.requireNonNull(((AppCompatActivity) Objects.requireNonNull(getActivity()))
.getSupportActionBar())
.setTitle(getString(R.string.your_title_here));
}
You have to override the method onBackPressed() and write the code:
#Override
public View onBackPressed(){
//Here goes the code that head back to your main fragment
FragmentTransaction fragmentTransaction3 = Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction();
Fragment fragment3 = new maintanance();
fragmentTransaction3.replace(R.id.container1, fragment3).addToBackStack(getString(R.string.menu_home)).commit();
}
}`
Add below code in Home Fragment...
#Override
public void onHiddenChanged(Boolean hidden) {
super.onHiddenChanged(hidden);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Home");
}

How to return to Previous Fragment by clicking back(Not Hardware back button)?

I have only 1 activity with 2 Fragments within it. When start the activity, Fragment A will launch. After user key in sth and click the button will direct to Fragment B. So what I want to do is that by adding a "Back Arrow" sth like this <- at the top left hand corner.
Does it has to do with FragmentManager.popBackStack()? Please advice ! Thx
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
first first=new first();
transaction.add(R.id.top,first);
transaction.commit();
}
}
first.java
public class first extends Fragment implements View.OnClickListener{
Button get_button;
EditText get_input_name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,container,false);
get_input_name=(EditText)rootView.findViewById(R.id.input_name);
get_button=(Button)rootView.findViewById(R.id.submit);
get_button.setOnClickListener(this);
return rootView;
}
public void onClick(View v){
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two();
Bundle bundle = new Bundle();
bundle.putString("input_name_value",get_input_name.getText().toString());
Two.setArguments(bundle);
transaction.replace(R.id.top,Two);
transaction.commit();
}
}
two.java
public class two extends Fragment implements View.OnClickListener {
TextView get_display_input;
ImageView get_back_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
get_display_input=(TextView)getActivity().findViewById(R.id.display_input);
get_back_button=(ImageView) getActivity().findViewById(R.id.back_button);
Bundle bundle = getArguments();
String get_name = bundle.getString("input_name_value");
//int store_get_input=Integer.parseInt(get_name);
get_display_input.setText("You have entered "+get_name);
}
public void onClick(View v){
// WHAT TO DO HERE IN ORDER TO RETURN TO PREVIOUS Fragment when clicking the button?
}
}
To be more precise, please refer to the screenshot.
You can do it by using the popBackStack() method of FragmentManager, put this inside the onClickListener of your back button :
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
}
If you're using the default back button of the toolbar i.e, the home button, then you can do it by placing this code in the onOptionsItemSelected() method of your Activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
}
return true;
}
return super.onOptionsItemSelected(item);
}
or, if you want the same behaviour on hardware back button press then override the onBackPressed() method in your Activity class like this:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Check out the training docs here -- they should give you a good start.
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
You just need this one single line of code!
getFragmentManager().popBackStackImmediate();
Yes, it has to do with FragmentManager.popBackStack();
Take a look here, there are plenty of methods:
https://developer.android.com/reference/android/app/FragmentManager.html#popBackStack
For me, getFragmentManager().popBackStackImmediate(); made exactly that.
In your Activity to handle hardware back button:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
So for button click method:
getFragmentManager().popBackStack();
Well I know I am too late to answer this but you can just call getActivity.onBackpress(); method on back click of that back icon.

How backPress works in fragment?

I am trying to use backpress on fragments. I am not able to fix it. Here is my code below.
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
if (position!=3){
pos = position;
}
switch (position) {
case 0:
fragment = new Profile();
break;
case 1:
fragment = new Products();
break;
case 2:
fragment = new Help();
break;
case 3:
DialogLogout(DrawerFragment.this, getString(R.string.logout), getString(R.string.cofirm_logout));
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(navMenuTitles[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
On Product Fragment I have list in which I again use to call another fragment.
listCards.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new Transactions();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
// .replace(R.id.frame_container, fragment)
.remove(Products.this)
.add(R.id.frame_container, fragment) //replace(R.id.frame_container, fragment)
.addToBackStack(null)
.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
return rootView;
}
BackPress functionality on DrawerFragmentActivity is like below:
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
if (count > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
Functionality would be like, DrawerFragmentActivity(Profile page by default)->Product->Transactions. Drawer Icon would be visible on Transactions screen as well, user can click my cards screen again while on transaction screen using drawer.
When user click on product it will again open transactions page, It's working fine. Now what happening is, when we click back on transaction it is coming on Product page, but When I again click on Product list screen(Frame) is overlapping with ProductsList and Transactions screen.
I am sorry if I it's confusing, Please ask if you don't understand. I can explain.
Thanks.
Fragment back press working code
public class ChiefFragment extends Fragment {
View view;
// public OnBackPressedListener onBackPressedListener;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.activity_chief, container, false);
getActivity().getActionBar().hide();
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(getTag(), "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getActionBar().show();
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// String cameback="CameBack";
Intent i = new Intent(getActivity(), home.class);
// i.putExtra("Comingback", cameback);
startActivity(i);
return true;
} else {
return false;
}
}
});
return view;
}
}
Use below code for back pressed in fragment.
public class DashBoard extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener(){
#Override
public boolean onKey(View v, int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().finish(); }
return true;
}
return false;
}
});
}
this code help you to implement your backpreesed in fragment.
I would recommend you to implement an interface to manage backstack. Here is a good blog post which would help you understand this process

Replacing Fragment does not change properly

The issue occurs when I attempt to switch from the Second Fragment to the First Fragment. I am using ActionBar Option Menu Icons to navigate back and forth between the different fragments.
Each fragment has its own menu that is associated with the individual option menu items. I cannot seem to figure out why I am able to transition from one the First Fragment to the Second Fragment, but am unable to do the reverse.
Does anything in my code stand out that would disable me from being able to navigate back to the previous fragment?
I was able to switch between the fragments without any issues in the past, but after I incorporated these option menu items to do the navigation, it stopped working.
Starting Fragment
public class SearchFragmentActivity extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_search_fragment,
container, false);
btnBasketball = (ImageButton) view.findViewById(R.id.btnBasketball);
btnBasketball.setOnClickListener(this);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
menu.clear();
inflater.inflate(R.menu.navigation_search_event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_more:
// do something with a dropdown
break;
}
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnBasketball:
changeFragment("Basketball");
break;
}
}
public void changeFragment(String sportName) {
Bundle bundle = new Bundle();
bundle.putString("SPORTNAME", sportName);
Fragment fragment = new SearchDetailsFragmentActivity();
fragment.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchFragment, fragment);
transaction.commit();
}
}
Second Fragment
public class SearchDetailsFragmentActivity extends Fragment {
TextView tvSportsName;
GridView gView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_search_details_fragment,
container, false);
String sportsName = getArguments().getString("SPORTNAME");
tvSportsName = (TextView) view.findViewById(R.id.tvSportsName);
tvSportsName.setText(sportsName);
// SportAdapter sAdapter = new SportAdapter(getActivity(), lstSports);
gView = (GridView) view.findViewById(R.id.gridViewSearch);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
menu.clear();
inflater.inflate(R.menu.navigation_search_details_event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_cancel:
changeFragment();
break;
}
return true;
}
public void changeFragment() {
Fragment fragment = new SearchFragmentActivity();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.commit();
}
}
Options Menu associated with Second Fragment
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/action_cancel"
android:icon="#drawable/ic_content_remove"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="always"/>
</menu>
UPDATES
These changes allow me to navigate backwards from the SearchDetailsFragmentActivity >> SearchFragmentActivity using the SoftKey Back Button.
Changes to the changeFragment() method inside SearchDetailsFragmentActivity
public void changeFragment() {
Fragment fragment = new SearchFragmentActivity();
FragmentManager fm = getFragmentManager();
//FragmentTransaction transaction = fm.beginTransaction();
//transaction.setCustomAnimations(R.anim.cell_left_in,
//R.anim.cell_right_out);
//transaction.replace(R.id.searchDetailsFragment, fragment);
//transaction.commit();
fm.popBackStack();
}
inside the SearchFragmentActivity
public void changeFragment(String sportName) {
Bundle bundle = new Bundle();
bundle.putString("SPORTNAME", sportName);
Fragment fragment = new SearchDetailsFragmentActivity();
fragment.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchFragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
UPDATE 2
I placed a Log.e inside the OnOptionItemSelected() to see if the button was even firing properly and it appears as if it is not. There is nothing that is getting logged.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_cancel:
Log.e("IS THIS WORKING", "THIS IS WORKING"); <<< NOT FIRING
changeFragment();
break;
}
return true;
}
When replacing a fragment, you need to indicate whether or not that transaction is reversable (i.e. whether or not it goes onto the backstack). For the first fragment transaction, you usually won't want to do this (wouldn't want to pop to an empty view). For fragment replacements, you want to specify addToBackStack() with an optional tag (which can be later used with popBackStack(String)).
For example, in between these lines:
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.commit();
add:
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.addToBackStack(null);
transaction.commit();

How to send data from main activity to fragment

public class MyActivity extends Activity implements ButtonFragement.OnFragmentInteractionListener, TextFragment.OnFragmentInteractionListener,Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ButtonFragement btnfrg=new ButtonFragement();
TextFragment txtfrg= new TextFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.my_activity,btnfrg,"Fragment");
ft.add(R.id.my_activity,txtfrg,"Second Fragment");
ft.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void respond(String data) {
FragmentManager fm=getFragmentManager();
TextFragment f1= (TextFragment) fm.findFragmentById(R.id.textfrg);
f1.changeText(data);
}
}
This is my main_Activity code, here i am trying to send a data over the fragment but it gives me error at f1.changeText(data).Basic structure of my project is , on main Activity , i created two fragment. One with button and another with text. I want to show how many times the button was clicked on second fragment using a communicator interface. Here in "data" counter shows a how many times button was clicked but i am not able to transfer it over second fragment.
Complete Code for the Program---
public interface Communicator {
public void respond(String data);
}
In TextFragment class i added this method----
public void changeText(String data)
{
txt.setText(data);
}
In ButtonFragment class i added and modified following method
public class ButtonFragement extends Fragment implements View.OnClickListener{
int counter=0;
private OnFragmentInteractionListener mListener;
Button btn;
Communicator comm;
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
comm= (Communicator) getActivity();
btn= (Button) getActivity().findViewById(R.id.button);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
counter++;
// comm.respond("The button was clicked "+counter+" times");
comm.respond("hi");
}
Here, i just added which i added in my program. My program get crash at...MainActiviy f1.changeText(data);
But why i am not getting it.Can anyone Help me fixed this bug?
Bundle bundle = new Bundle();
bundle.putString("key", value);
// set Fragmentclass Arguments
YourFragment ff= new YourFragment ();
ff.setArguments(bundle);
transaction.add(R.id.my_activity, ff);
Using Bundle
From Activity:
Bundle bundle = new Bundle();
bundle.putString("message", "Hello!");
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
String myValue = this.getArguments().getString("message");
...
...
}
You have no fragment with id R.id.textfrg.
You are for some reason adding two fragments with id R.id.my_activity. One with tag "Fragment" and another with tag "Second Fragment".
So you are getting error.
Your idea is rigth.
This may be helpfull
TextFragment f1= (TextFragment) fm.findFragmentByTag("Second Fragment");
DO this way:
On Activity Side.
Fragment fragment = new GridTemplate();
Bundle bundle = new Bundle();
bundle.putInt("index",your value);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
here R.id.frame_container is a frame Layout or Relative Layout In which you have to add the fragment.
On Fragment Side.
int index = getArguments().getInt("index");
hope this wil solve your problem. Thanks

Categories

Resources