I have 4 fragments inside my viewpager and I want to get the edit text value from another fragment. E.g :
I'm in the third fragment and I want to get the value of the Edit text inside the first fragment.
How can I do to do that ?
Interface is your best option.
As the fragment in viewpager is recreated every time. you cannot store values inside fragment and get it properly.
Create variable to hold editext value in ViewPager Hosting Activity.
String editext_fragment1;
Use Interface to write and get values from this variable from any fragments .
Try getActivity().findViewById(), if you are not re-using the same id anywhere in other fragments. Check if it is null or not, then use it.
Hope it will help :)
In your MainActivity create a function and a global variable (setter and getter)
private EditText mEditText;
public EditText getEditText(){
return mEditText;
}
public void setEditText(EditText et){
this.mEditText = et;
}
In your FirstFragment
((MainActivity) getActivity()).setEditText(YOUR_EDITTEXT);
In your ThirdFragment where you need to get the EditText value
if( ((MainActivity) getActivity())getEditText() != null ){
((MainActivity) getActivity())getEditText().getText();
}
To do that you should pass your value through the constructor of your fragment.
For exemple you have your first fragment with a button that will call the secondFragment:
public class myFirstFragment extends Fragment implements View.OnClickListener {
private Button myButton;
private EditText myEdit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.myFirstFragment_layout, container, false);
myButton = (Button) rootView.findViewById(R.id.buttonId);
myEdit = (EditText) rootView.findViewById(R.id.editTextId);
myButton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
Fragment fragment;
switch (v.getId()) {
case R.id.buttonId:
fragment = new mySecondFragment(myEdit.getText().toString().trim());
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contenedor_frag, fragment).commit();
}
}
And in your second Class you should have this:
public class mySecondFragment extends Fragment {
private String myEditFirstFragment;
public mySecondFragment (String _editFirstFrag) {
this.myEditFirstFragment = _editFirstFrag;
}
}
Hope that helps,
Related
I'm trying to make an app where I've a RecyclerView with the options to remove the objects and add random numbers. What I'm trying to do is show a fragment when any member of the recycler view list is clicked. I'm getting the error " java.lang.IllegalStateException: Activity has been destroyed".
I'm pretty shure I'm doing something very wrong.
What I tried to do is putting a call to the change fragment method on my AnimalsAdapter class. I'm letting the code below and a github link.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.berna.recyclerviewtp2, PID: 18705
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2114)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:637)
at com.example.berna.recyclerviewtp2.MainActivity.changeFragment(MainActivity.java:148)
at com.example.berna.recyclerviewtp2.AnimalsAdapter$1.onClick(AnimalsAdapter.java:81)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
My Code Main class changeFragment:
public void changeFragment(View view){
Fragment fragment;
FragmentOne fragmentOne = new FragmentOne();
fragment = fragmentOne;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment,fragment);
ft.addToBackStack(null);
ft.commit();
FragmentOne class code:
public class FragmentOne extends Fragment {
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState){
//Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank,container,false);
}
}
Click Listener code:
// Set a click listener for TextView
holder.mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new MainActivity().changeFragment(view);
//String animal = mDataSet.get(position);
//Toast.makeText(mContext,animal,Toast.LENGTH_SHORT).show();
}
});
What I have to do to achieve the fragment when pressing the recyclerview member?
Original code I'm using to try what I'm trying
Github link for complete project
You should never instantiate your activity this way: new MainActivity().changeFragment(view);, it will never initialise properly. So it's either you delegate the listener, or find another work around for the callback.
For example, create an interface for callback:
interface ItemClickListener {
void onItemClick(View v);
}
Let your MainActivity implements the interface:
public class MainActivity extends Activity implements ItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
mAdapter = new AnimalsAdapter(mContext, animalsList, this);
// ...
}
#Override
public void onItemClick(View view) {
changeFragment(view);
}
}
Then allow your adapter to take ItemClickListener as a parameter:
private ItemClickListener callback;
public AnimalAdapter(Context context, List<String> data, ItemClickListener callback) {
this.callback = callback;
And let your holder.mTextView to forward the callback (back to activity):
holder.mTextView.setOnClickListener(callback::onItemClick);
You should create fragment after activity created, that is a basic knowledge about activity life cycle.
holder.mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(your_current_activity, MainActivity.class);
intent.putExtras(extras);
startActivity(intent);
}
});
then replace fragment in onCreate() of MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
changeFragment(null); //because we don't using parameter view
}
If you have any problem else, please comment below.
You need two changes in your code.
1. Create an interface for click listener.
2. If you want to replace fragment then you need one more Layout in XML
We solve the first issue.
1. Create an interface for click listener.
Below are some change you need to do in your adapter,
Create Interface in your adapter
public interface RecyclerItemInteraction {
void onChangeFragmentClick();
}
The second change will pass this interface.
Deeclare gloabal variable
private RecyclerItemInteraction mInteraction;
public AnimalsAdapter(Context context,List list,RecyclerItemInteraction interaction){
mDataSet = list;
mContext = context;
mInteraction = interaction;
}
Replace this below line
new MainActivity().changeFragment(view); : Remove it
if (mInteraction!=null)mInteraction.onChangeFragmentClick(); add this line.
Now Go to your MainActivity and add below line
mAdapter = new AnimalsAdapter(mContext, animalsList,this);
You can see that add third parameter this.
Now override this method and enjoy your day.
#Override
public void onChangeFragmentClick() {
Fragment fragment;
FragmentOne fragmentOne = new FragmentOne();
fragment = fragmentOne;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container,fragment);
ft.addToBackStack(null);
ft.commit();
}
If you want to replace fragment then you need one more Layout in XML
Add this line to your main_activity.xml layout.
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.
i am just working with fragments for the 1st time, i have a checkbox inside a fragment and a submit button inside my main activity. what i want to do is when i press submit button i want to toast a message whether the checkbox item is checked or not?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Spinner Dspinner;
private Button Subbtn;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Subbtn = (Button)findViewById(R.id.button);
adapter = ArrayAdapter.createFromResource(this, R.array.spinner_options, android.R.layout.simple_spinner_item);
spinnerListner();
}
public void spinnerListner(){
Dspinner = (Spinner)findViewById(R.id.spinner);
Dspinner.setAdapter(adapter);
Dspinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
getSupportFragmentManager().beginTransaction().replace(R.id.frag, BlankFragment.newInstance()).addToBackStack(null).commit();
break;
case 1:
getSupportFragmentManager().beginTransaction().replace(R.id.frag, BlankFragment2.newInstance()).addToBackStack(null).commit();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
}
}
BlankFragment.java
public class BlankFragment extends Fragment {
public BlankFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
public static Fragment newInstance() {
BlankFragment fragment = new BlankFragment();
return fragment;
}
}
BlankFragment2.java
public class BlankFragment2 extends Fragment {
public BlankFragment2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank_2, container, false);
}
public static Fragment newInstance() {
BlankFragment2 fragment = new BlankFragment2();
return fragment;
}
}
You can use interface to communicate back to MainActivity.
Create a interface and implement it on MainActivity.
Pass the implemented interface to fragment and store it in the fragment
Then When your checkbox state change check that the stored interface is null or not if not null then call the implemented method
of the interface, which is actually implemented in MainActivity.
This way you can communicate back to MainActivity. In MainActivity store your checkbox state and do what you want to do in button press.
Interface
public interface OnStateChanged {
public void onChange(int state);
}
Implement it on MainActivity like
MainActivity implements OnStateChanged {
#Override
public void onChange(int state){
// store your data here
}
Create a variable for OnStateChanged interface and function in Fragment that will pass the interface
In Fragment:
OnStateChanged mListener;
public void setOnStateChangeListener(OnStateChanged listener){
mLinstener = listener;
}
When checkbox state change call the interface function
In Fragment:
//...if state change...
if(mListener!= null) {
mListener.onChange(/*your value*/);
}
Pass the implemented interface instance in MainActivity to fragment
In MainActivity:
fragment.setOnStateChangeListener(this);
There are several ways to realize this function. The easiest way is Defining an interface in your Activity, and let the Fragment implements it.(Or you can define a interface individually and let the Activity implements it, it's the similar solution)
For more solutions you can Google "Fragment and Activity Interaction".
I just can offer you some fragmentary code since I cannot find specific variable names.
First, defining a Interface in your Activity like this:
public static class MainActivity extends AppCompatActivity{
...
//Container Activity must implement this interface
public interface CheckBoxStateCallback{
public Boolean getTheState();
}
...
Second, let your fragments implements it:
public class BlankFragment extends Fragment implements CheckBoxStateCallback{
public BlankFragment(){
}
#Override
public Boolean getTheState(){
//return your checkbox state
}
...
Last, you need to add a click listener onto your Button in Activity:
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean b = BlankFragment.newInstance().getTheState();
//then you can make a toast
}
});
...
In MainActivity you would implement an interface CheckboxStatusObserver which we define with a method checkBoxChanged.
public class MainActivity extends AppCompatActivity implements CheckboxStatusObserver{
// other methods
void checkBoxChanged(boolean checkedStatus){
Toast.makeText(getContext(), "status " + checkedStatus, Toast.LENGTH_LONG).show();
}
public interface CheckboxStatusObserver{
void checkBoxChanged(boolean checkedStatus);
}
}
In the Fragment, we would get a reference to the CheckboxStatusObserver as the parent Activity. Then while inflating the contents of the Fragment, we can set up a listener to detect the on change of the checkbox(s). Then we would call the observer.checkBoxChanged(checkedStatus); and pass it the checked status of the checkbox.
public class BlankFragment extends Fragment {
private CheckboxStatusObserver observer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
observer = (CheckboxStatusObserver) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
// Find the checkbox instace using view.findViewById();
// Setup change listener on checkbox instance and notify the observer
{
observer.checkBoxChanged(checkedStatus);
}
return view;
}
}
Whenever the checkbox status changes, the method in the MainActivity will get invoked.
See below links for more information:
https://stackoverflow.com/a/25392549/592025
https://developer.android.com/training/basics/fragments/communicating.html
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
Create an Interface in Your MainActivity and click listeners as below
try {
((OnClick) this).onSubmitClicked();
} catch (ClassCastException cce) {
cce.printStackTrace();
}
public interface OnClick {
public void onSubmitClicked();
}
Now implement listeners in your Fragment thus you will get onSubmitClicked implemented method as below Enjoy!
public class BlankFragment extends Fragment implements MainActivity.OnClick{
#Override
public void onSubmitClicked() {
//do something here
}
}
This is yet another way different from what i commented that day this might meet your need
In Main Activty
Blank1Fragment fragment1 = new Blank1Fragment();
Blank2Fragment fragment2 = new Blank2Fragment();
Subbtn..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(position==0)
fragment1.function();
else if(position==1)
fragment2.function();
}
);
in OnitemClick of spinner
switch (position){
case 0:
position=0;
getSupportFragmentManager().beginTransaction().replace(R.id.frag, fragment1).addToBackStack(null).commit();
break;
case 1:
position=1;
getSupportFragmentManager().beginTransaction().replace(R.id.frag, fragment2).addToBackStack(null).commit();
break;
}
}
Each fragment will have
public class Blank1Fragment extends Fragment {
....
public void function(){
//check which checkbox selected and toast;
}
}
public class Blank2Fragment extends Fragment {
....
public void function(){
//check which checkbox selected and toast;
}
}
I want to know how to get data from 2 different fragments inside tab layout.
For example: In this image there two tabs tab1 and tab2 both have different values stored in edit text .
tab1 helloooooo,
tab2 hiiiiiii
and i have a button available in main activity which is used for getting the data from both tabs in same time.
Now my Problem is How i can get the data from both tabs at same time when user click on the
get data button
1.) Keep a reference of your fragment in your activity.
public class Activity extends AppCompatActivity {
private yourFargment frag1,frag2;
}
2.) Get the object reference into your reference variables in Adapter's getItem().
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
frag1 = yourFargment.newInstance(index);
//frag1 =new yourFargment (); can also be used
return frag1;
case 1:
frag2 = yourFargment.newInstance(index);
return frag2;
}
return null;
}
3.) Inside your onClick you can simply get those values from edittext.
onClick(View..){
String val1 = frag1.edittext1.getText().toString(); // Note: make your `edittext` public
String val2 = frag2.edittext2.getText().toString();
or
String val1 = frag1.getData();
String val2 = frag2.getData();
}
where getData is a public method inside your fragment
public class yourFragment..{
public String getData(){
return edittext.getText().toString();
// Note: with this no need to make your `edittext` public
}
}
Take member object of both Fragment in your activity..
FirstFragment mFirstFragment;
SecondFragment mSecondFragment;
Create instance of both in getItem(int position) method of ViewPagerAdapter.
#Override
public Fragment getItem(int position) {
// instantiate the fragment for the given page.
switch (position) {
case 0:
if (null == mFirstFragment) {
mFirstFragment = FirstFragment.newInstance();
}
return mFirstFragment;
case 1:
if( null == mSecondFragment ) {
mSecondFragment = SecondFragment.newInstance();
}
return mSecondFragment;
}
return null;
}
Call getData method of both Fragment when button clicked from activity.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// Get data and use it as you want.
mFirstFragment.getData();
mSecondFragment.getData();
break;
}
}
At the time when you are settings fragment in tabs you have 2 objects of those fragments. By using those objects, you can retrieve the value from your fragments. Write following code into your MainActivity e.g.
if(tab1fragment != null) {
String text = tab1fragment.getData();
}
and in Fragment, create a method like
public String getData(){
return edittext.getString().toString();
}
This way you can retrieve the data from fragments.
Tablayout only contains TabItems not Fragment. So, I believe that you use TabLayout combines with ViewPager, which actually contains 2 different Fragments. I suppose maybe you want to getData() at the Activity from 2 Fragments. At this point, you can easily Fragment callback the Activity and provide data just like getData(). The code will look like
In Fragment
public class BaseFragment extends Fragment {
protected DataCallback mCallback;
#Override public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof DataCallback) {
mCallback = (DataCallback) context;
}
}
//some place fragment affect to data
private void someFunction() {
mCallback.updateDataToActivity(data);
}
}
In Activity
public class MyActivity extends BaseActivity implements DataCallback {
T data;
public void updateDataToActivity(T data) {
this.data = data
}
// This is your getData function
private T getData() {
return data;
}
}
And DataCallback
public interface DataCallback {
void updateDataToActivity(T data);
}
You can use like this way:
Bundle bundle = new Bundle();
bundle = getActivity().getIntent().getExtras();
YourFragment fragment = new YourFragment();
bundle.putString("yourKey", yourValue);
fragment.setArguments(bundle);
Then you can get them in your second fragment
in onCreateView
if (getArguments() != null)
{
mParam1 = getArguments().getString("yourKey");
}
You can use data bus library like Otto : http://square.github.io/otto/
Or Rxjava : https://github.com/ReactiveX/RxJava
Both of these libraries are made for propagate data between classes.
Each tab has an EditText with an id
in tab1.xml it's edit1
<EditText
android:id="#+id/edit1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
and it's edit2 in tab2.xml
<EditText
android:id="#+id/edit2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
tab1.xml and tab2.xml also has a button which can be clicked. It has the same id if you want on tab1 and tab2.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/knop"
android:onClick="klik"/>
The item that matters is the OnClick. It point to a piece of code which must be implemented in the MainActivity.java code
public void klik(View v){
alert("Just an alert.");
String val1 = ((EditText) findViewById(R.id.edit1)).getText().toString();
String val2 = ((EditText) findViewById(R.id.edit2)).getText().toString();
alert(val1);
alert(val2);
alert(val1 + val2);
}
At last the alert routine
private void alert(String message){ //mies
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
In fact the fragments can be treated as one page. You can retrieve the information from each field by id from the calling main page, in this case MainActivity.java.
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