Reputation: 2061
Hi i am very new for android in my app i have created Two fragments they are "MenuFragment" and "TextFragment" ok that's fine
But in my TextFragment i have one Method so that i want call that method from my MenuFragment class
public void change(String txt, String txt1) method i want to call from my MenuFragment
how can i do this please help me some
public class TextFragment extends Fragment {
TextView text,vers;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
return view;
}
public void change(String txt, String txt1){
text.setText(txt);
vers.setText(txt1);
}
}
public class MenuFragment extends Fragment {
String[] AndroidOS = new String[]{"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream SandWich", "Jelly Bean", "KitKat", "Jelly Bean", "KitKat"};
String[] Version = new String[]{"1.5", "1.6", "2.0-2.1", "2.2", "2.3", "3.0-3.2", "4.0", "4.1-4.3", "4.4", "4.1-4.3", "4.4"};
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
Upvotes: 1
Views: 4620
Reputation: 687
You can try this.
For TextFragment:-
public class TextFragment extends Fragment{
public static TextView text,vers;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public static void change(String txt, String txt1){
text.setText(txt);
vers.setText(txt1);
}
}
For MenuFragment:-
public class MenuFragment extends Fragment {
ListView list;
Button button1, button2;
String[] AndroidOS = new String[]{"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream SandWich", "Jelly Bean", "KitKat", "Jelly Bean", "KitKat"};
String[] Version = new String[]{"1.5", "1.6", "2.0-2.1", "2.2", "2.3", "3.0-3.2", "4.0", "4.1-4.3", "4.4", "4.1-4.3", "4.4"};
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextFragment.change(AndroidOS[position],Version[position]);
}
}
I hope This will help you.Thanks
Upvotes: 3
Reputation: 2509
Its not a good idea to leave communication betweeen two fragments like this, because you are coupling the fragments
; TextFragment
should not know about methods from MenuFragment
.
A better solution is described in here: http://developer.android.com/guide/topics/fundamentals/fragments.html
You must create Activity
for these two fragments
and make call back
for comunication
Upvotes: 1
Reputation: 91
This is irrelevant to Android as such, you need to get better understanding what are classes, objects, pointers, etc. -- all general OOP concepts.
To achieve your result you need to add a variable-pointer to an object of class TextFragment, which has to be properly initialized before use. Then just call:
if(varPtr!=null)
varPtr.change(...);
Upvotes: 0