Communicating between Fragment and Activity - android

I have a fragment with multiple toggle buttons. On click of a particular button in my Activity, I'd like to upload the status of all these toggle buttons to the server. I see there is one way of doing it as explained in the below link, where we create a listener interface and on every click of each toggle button, we update some tag/integer in the activity corresponding to each toggle button.
https://developer.android.com/training/basics/fragments/communicating.html
But I would like to know if there is any way to know the checked/unchecked status of all toggle buttons in the fragment from the activity without implementing the interface methods for each time a toggle button is clicked. Hope I'm clear.

Here's a working example of how to achieve that. The activity:
public class MainActivity extends AppCompatActivity {
ToggleFragment toggleFragment;
Button updateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
updateStatusButton = (Button) findViewById(R.id.updateStatusButton);
toggleFragment = ToggleFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_frame, toggleFragment, "ToggleFragment")
.commit();
updateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean buttonsChecked = toggleFragment.areToggleButtonsChecked();
Toast.makeText(MainActivity.this, String.format("Toggle buttons checked: %s", buttonsChecked), Toast.LENGTH_LONG).show();
}
});
}
}
And the Fragment:
public class ToggleFragment extends Fragment {
ToggleButton toggleButton1;
ToggleButton toggleButton2;
ToggleButton toggleButton3;
public static ToggleFragment newInstance() {
Bundle args = new Bundle();
ToggleFragment fragment = new ToggleFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.toggle_fragment, container, false);
toggleButton1 = (ToggleButton) view.findViewById(R.id.toggleButton1);
toggleButton2 = (ToggleButton) view.findViewById(R.id.toggleButton2);
toggleButton3 = (ToggleButton) view.findViewById(R.id.toggleButton3);
return view;
}
public boolean areToggleButtonsChecked() {
return toggleButton1.isChecked()
&& toggleButton2.isChecked()
&& toggleButton3.isChecked();
}
}

Honestly, the best way that you could accomplish this is with a ViewModel from the Android Architecture Components library. The ViewModel can have an ObservableField or LiveData value that each of the Fragments can observe, and always have the correct information. This would also make it easier to be lifecycle-aware.

Related

Is it possible to convert Blank Activities to Fragment Activities

I currently have an Unit Converter app that I'm working in.
Here I've used multiple Blank Activities. Where each Unit's Activity can be opened using MainActivity. But now I want to make it tablet friendly.
Hence I want to use FragmentActivity now. Is it possible to convert the Blank Activities to Fragment Activities.?
All you need to do is take all View-specific logic from the Activity to a Fragment, then load the Fragment in your Activity.
For example,
public class MainActivity extends Activity {
#InjectView(R.id.button)
public Button button;
#OnClick(R.id.button)
public void onButtonClick(View view) {
Toast.makeText(this, "Hello!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
}
This type of logic goes in
public class MainFragment extends Fragment {
#InjectView(R.id.button)
public Button button;
#OnClick(R.id.button)
public void onButtonClick(View view) {
Toast.makeText(this, "Hello!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.inject(this, view);
return view;
}
}
And your Activity needs to display this fragment either statically, or dynamically. If you go dynamical, you'll need the following lines in your Activity:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
if(savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
}
}
If you go static, then you need to specify the fragments in your layout XML for the activity.
http://developer.android.com/guide/components/fragments.html#Adding
I would visit the Android website as they give a fairly good explanation on how fragments work.
You can learn how to add them to your existing application by another Android link here.

Getting value from Fragment into mainActivity

I have a MainActivity. It's layout contains a fragmentContainer and an actionBar. Then I have 2 different fragments containing various EditTexts.All of them have Ids. I populate the fragmentContainer with the fragments when user clicks a button in actionBar. Everything works perfectly.
Now...the app, is supposed to collect the contents of all EditTexts from both fragments when I push a button (in the menu of the actionBar). But it does not work. It crashes when I try to access the EditTexts directly from the activity. I understand that I should create a public method inside the code of the fragments that will return the values I am interested in. But I seem to be doing something wrong because the method is not accessible from the main (TabActivity)
Here is my code:
public class TabActivity extends Activity {
ActionBar.Tab tab_alocare, tab_merc;
Fragment fragmentTab1 = new aloc_fragment();
Fragment fragmentTab2 = new merc_fragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab); // this layout contains the fragmentContainer
...// here I do some actionBar stuff
}
...
}
An example of one of the fragments is bellow:
public class aloc_fragment extends Fragment {
EditText mEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_aloc, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mEditText = (EditText) getView().findViewById(R.id.edaloc);
}
public String getMyText() {
String rez = "";
if (mEditText.getText()!=null) {
rez = mEditText.getText().toString();
}
return rez;
}
}
Now... if inside the Activity code I want to access the edaloc EditText using findViewById, it crashes the app with nullException. So I then tried to access the public method of the fragment so that it would return me the value that I need. But "getMyText" method is not accessible from the TabActivity.
So, this code does not work:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
Fragment alocfragment = (Fragment) getFragmentManager().findFragmentByTag("aloc");
String s = alocfragment.getMyText(); // this is not compiling at all
I am clearly doing something wrong.
Please advise.
Thank you
There are lots of mistakes in your code, You have neither declared nor initialize the fragments at proper place. Also, you are trying to create another instance of fragment in onOptionsItemSelected which is wrong, you need to use same instance of fragment there to access your functions with values. I hope you know how to add and inflate fragment. See my comments and code changes.
Try with this -
public class TabActivity extends Activity {
ActionBar.Tab tab_alocare, tab_merc;
//Declare fragments here
Fragment fragmentTab1;
Fragment fragmentTab2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab); // this layout contains the fragmentContainer
//Initialize here
fragmentTab1 = new aloc_fragment();
fragmentTab2 = new merc_fragment();
//inflate/add fragments here to the activity
...// here do your actionBar stuff
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
//Now, use same instance of fragment to access your function
String s = fragmentTab1.getMyText();
}
}
public class aloc_fragment extends Fragment {
EditText mEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_aloc,
container, false);
//hold edittext here in the variable
mEditText = (EditText) view.findViewById(R.id.edaloc);
return view;
}
public String getMyText() {
String rez = "";
if (mEditText.getText()!=null) {
rez = mEditText.getText().toString();
}
return rez;
}
}
Also, must to go through Fragment tutorial on Android Developer Fragment Link Link 2, Using Fragments

New Activity created every time Button is pressed

I am making an app that will has three activities. The user can navigate to a new activity pressing buttons (home, graph, and write). This part works fine, but I only want three activities to be created max. Right now if I push the buttons 10 times I get 10 separate activities. Is there a way to prevent this and have the button call an activity if it has already been created instead of creating a new one each time?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_toGraph = (Button) findViewById(R.id.home_to_graph);
button_toGraph.setOnClickListener(goToSecondListener);
Button button_toWrite = (Button) findViewById(R.id.home_to_write);
button_toWrite.setOnClickListener(goToThirdListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener goToSecondListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
doButton();
}};
private void doButton()
{
startActivity(new Intent(this, GraphScreen.class));
}
private OnClickListener goToThirdListener = new OnClickListener(){
#Override
public void onClick(View v) {
doBacktoThird();
}
private void doBacktoThird() {
startActivity(new Intent(MainActivity.this, WriteScreen.class));
}
};
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Any help will be greatly appreciated! Thank you!
create three Boolean Variables.
if suppose button_toGraph is clicked .. make the
Boolean button_toGraph_IsCreated = true;
and when Activity is Finished ( YourActivity.finish ) make it Again false.
make a check on the button by using these variable like
if(button_toGraph_IsCreated) // if the variable is true
{
// do nothing as already activity created
}
else
{
doBacktoThird();
}
if you are using database then it should not be hard to get the values to main activity.

Android buttons' onClickLIstener() only works once when the Activity begins, not when returning from Fragment transaction

Any time the main Activity is started or restarted (i.e. by pressing the home button on my action bar), all of the buttons (which reside in a fragment in this main activity) work correctly. However, if I press one of the buttons, then press the back button, the home fragment and its buttons reappears but none of the button callbacks work. The button images continue to change appearance when pressed, as always.
The callbacks are assigned in the onCreateView method of the home fragment, as follows:
public class HomeFragment extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d(TAG, "Button!");
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.contFragMain, new SomeFragment())
.addToBackStack(null)
.commit();
}
});
}
Here is the superclass of Fragments I launch with the buttons:
public abstract class RouteListFragment extends SherlockFragment {
private static final String TAG = RouteListFragment.class.getName();
private Activity mActivity; // parent activity
RouteListAdapter mAdapter;
ListView mListViewRouteList;
public RouteListFragment() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bndl = getArguments(); // data passed should contain search term
View v = inflater.inflate(R.layout.fragment_route_list, container, false);
mListViewRouteList = (ListView) v.findViewById(R.id.listViewRouteList);
addRoutesToList(); //Populates the list with data via an async DB call
return v;
}
You shouldn't be stashing the Activity reference; the Activity is probably getting recreated at some point (depends on how your flow is), but you should either reassign the reference in onAttach (Activity activity), or just call getActivity() to get the currently Activity you're attached to.
So mActivity.getSupportFragmentManager()...
should instead be
getActivity().getSupportFragmentManager()...
EDIT: Wait, maybe that's not right. What is v in onCreateView()? You're not creating any UI in this Fragment? You should be using onViewCreated() to get a reference to the views in the created hierarchy.

onClick inside fragment called on Activity

i am encapsulating stuff into a fragment at the moment and run into a problem that is hard to google.
Inside my fragment are some buttons with onClick attributes but they are called on the Activity rather the fragment from the android system - this makes encapsulating a bit clumsy. Is there a way to have the reflection stuff from onClick to call on the fragment? The only solution to this I see at the moment is not to use onClick in the xml and set click-listeners inside the fragment via code.
I spoke to some googlers # #adl2011 - they recognize the problem and perhaps there will be a fix of that in the future. Until then - one should use .setOnClick in the Fragment.
The problem is that when layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments.
I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well.
public class StartFragment extends Fragment implements OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
Button b = (Button) v.findViewById(R.id.StartButton);
b.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
...
break;
}
}
}
Then problem is gone.
It works for me
Add import:
import android.view.View.OnClickListener;
Fragment.java
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater.inflate(R.layout.fragment, container, false);
Button mButton = (Button) rootView.findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return rootView;
}
ISSUE:
1.In XML onClick attribute will call activity's public method.
2.Fragment's public method not called.
3.Fragment reusability.
SOLUTION:
In Fragment's layout add this to the View.
android:onClick="onFragmentViewClick"
In each activity the fragment may belong..
public void onFragmentViewClick(View v) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (fragment != null && fragment.isVisible()) {
if (fragment instanceof SomeFragment) {
((SomeFragment) fragment).onViewClicked(v);
}
}
}
In the Fragment include this method..
public void onViewClicked(View v) {
switch (v.getId()) {
case R.id.view_id:
Log.e("onViewClicked", "yehhh!!");
break;
}
}
You could have the listener that is being called in the activity forward the call onto a listener in the fragment. You should have a reference to the fragment inside of the FragmentActivity to pass the call on. You will have to cast to call the method or have your fragment implement an interface you define. I know that isn't the best solution but it will work. You could also use the tag of a button to specify the method name to call if you wanted. Hope this helps a bit.
Try this...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_ipadditional_users, container, false);
FloatingActionButton button7 = (FloatingActionButton) rootView.findViewById(R.id.fab_ip_additional_user);
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), IPAdditionalUsersEdit.class);
startActivity(intent);
}
});
return rootView;

Categories

Resources