I have a project extend Fragment
Now, My project have three tabs.
it was composition fragment.
Write!!!! edittext in first tab → Push!!!! Add button → View!!!! listview in second tab
please.. help me!!
final Button btn1 = (Button) view.findViewById(R.id.ButtonAdd);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = mEditMAC.getText().toString();
});
public View getView(int position, View convertView, ViewGroup parent) {
return parent;
Basic communication between fragments is
fragment -> activity -> another fragment
Here is sample code for callback from fragment to activity.
You can find more detail code in the http://developer.android.com/training/basics/fragments/communicating.html
FirstFragment
public class FirstFragment extends Fragment {
public interface OnBtnClickListener {
public void buttonClicked(String mac);
}
OnBtnClickListener mCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnBtnClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnBtnClickListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// initialize
// ...
final Button btn1 = (Button) view.findViewById(R.id.ButtonAdd);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = mEditMAC.getText().toString();
mCallback.buttonClicked(str);
}
});
}
}
Activity
public class YourActivity extends Activity implements FirstFragment.OnBtnClickListener {
#Override
public void buttonClicked(String mac) {
// find second fragment and call the proper function
SecondFragment fragment = (SecondFragment)getSupportFragmentManager().findFragmentByTag(SecondFragment.TAG);
if (fragment != null) {
fragment.buttonClicked(mac); // update second fragment's listview
}
}
}
Related
This is the code for the fragment. Please help me place a button and onClick it should go to the respective activity
class boards extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.boards, container, false);
}
}
Inside onViewCreated method:
View view = inflater.inflate(R.layout.boards, container, false);
Button button = (Button) view.findViewById(R.id.buttonId);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
// do something
startActivity(new Intent(getActivity(), YourActivity.class));
}
});
return view;
you need to implement a call back interface
interface code :
public interface FragmentCallback {
void changeActivity();
}
inside fragment:
FragmentCallback mListener;
void setListener(FragmentCallback listener){
mListener=listener;
}
inside activity:
public class Activity extends AppCompatActivity implements FragmentCallback{
Boards fragment=new Boards(); //class name shoud be capital i.e Boards
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
fragment.setListener(this);
}
#Override
void changeActivity(){
Intent intent =new Intent(this,newActivity.class);
startActivity(intent);
}
}
use the below code to change activity from fragment :
if(mListener!=null)
mListener.changeActivity()
below code will do the task
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 have an Activity1 that shows a custom dialogfragment- ExampleDialog. I have implemented a listener, SubmitDialogListener for the dialogfragment to communicate with the activity using onSubmit(). In onSubmit(), I am showing some other dialogfragment. My question is, if I show the same ExampleDialog Fragment from Activity2, should Activity2 implement the SubmitDialogListener interface and implement the onSubmit() method in Activity2 again? Or is there a better way to define the onSubmit() method?
import android.support.v4.app.DialogFragment;
// ...
public class Activity1 extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
......
showDialog();
}
private void showDialog() {
FragmentManager fm = getSupportFragmentManager();
ExampleDialog exDialog = ExampleDialog.newInstance("Some Title");
exDialog.show(fm, "fragment_edit_name");
}
#Override
public void onSubmit() {
//open new fragments
}
}
public class ExampleDialog extends DialogFragment implements SubmitDialogListener {
public interface SubmitDialogListener {
void onSubmit();
}
public ExampleDialog() {
// Empty constructor required for DialogFragment
}
public static ExampleDialog newInstance(String title) {
ExampleDialog frag = new ExampleDialog();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_name, container);
.........
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SubmitDialogListener listener = (SubmitDialogListener) getActivity();
listener.onSubmit();
dismiss();
}
});
return view;
}
}
In this case the Activity should implement the SubmitDialogListener not the Dialog Fragment, like this:
public class Activity1 extends ActionBarActivity implements SubmitDialogListener {
#Override
public void onSubmit() {
//open new fragments
}
}
And if you want to use the same dialog fragment in multiple activities, it's generally best to create it in a separate class file.
I have a Fragment FR1 that contains several Nested Fragments; FRa, FRb, FRc. These Nested Fragments are changed by pressing Buttons on FR1's layout. Each of the Nested Fragments have several input fields within them; which include things like EditTexts, NumberPickers, and Spinners. When my user goes through and fills in all the values for the Nested Fragments, FR1 (the parent fragment) has a submit button.
How can I then, retrieve my values from my Nested Fragments and bring them into FR1.
All Views are declared and programmatically handled within each Nested Fragment.
The parent Fragment, FR1 handles the transaction of the Nested Fragments.
I hope this question is clear enough and I am not sure if code is necessary to post but if someone feels otherwise I can do so.
EDIT 1:
Here is how I add my Nested Fragments:
tempRangeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getChildFragmentManager().beginTransaction()
.add(R.id.settings_fragment_tertiary_nest, tempFrag)
.commit();
}
});
scheduleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getChildFragmentManager().beginTransaction()
.add(R.id.settings_fragment_tertiary_nest, scheduleFrag)
.commit();
}
});
alertsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getChildFragmentManager().beginTransaction()
.add(R.id.settings_fragment_tertiary_nest, alertsFrag)
.commit();
}
});
submitProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
constructNewProfile();
}
});
where my constructNewProfile() method needs the values from my Nested Fragments.
public Fragment tempFrag = fragment_profile_settings_temperature
.newInstance();
public Fragment scheduleFrag= fragment_profile_settings_schedules
.newInstance();
public Fragment alertsFrag = fragment_profile_settings_alerts
.newInstance();
The above refers to the fields of the parent fragment; and how they are initially instantiated.
The best way is use an interface:
Declare an interface in the nest fragment
// Container Activity or Fragment must implement this interface
public interface OnPlayerSelectionSetListener
{
public void onPlayerSelectionSet(List<Player> players_ist);
}
Attach the interface to parent fragment
// In the child fragment.
public void onAttachToParentFragment(Fragment fragment)
{
try
{
mOnPlayerSelectionSetListener = (OnPlayerSelectionSetListener)fragment;
}
catch (ClassCastException e)
{
throw new ClassCastException(
fragment.toString() + " must implement OnPlayerSelectionSetListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
onAttachToParentFragment(getParentFragment());
// ...
}
Call the listener on button click.
// In the child fragment.
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.tv_submit:
if (mOnPlayerSelectionSetListener != null)
{
mOnPlayerSelectionSetListener.onPlayerSelectionSet(selectedPlayers);
}
break;
}
}
Have your parent fragment implement the interface.
public class Fragment_Parent extends Fragment implements Nested_Fragment.OnPlayerSelectionSetListener
{
// ...
#Override
public void onPlayerSelectionSet(final List<Player> players_list)
{
FragmentManager fragmentManager = getChildFragmentManager();
SomeOtherNestFrag someOtherNestFrag = (SomeOtherNestFrag)fragmentManager.findFragmentByTag("Some fragment tag");
//Tag of your fragment which you should use when you add
if(someOtherNestFrag != null)
{
// your some other frag need to provide some data back based on views.
SomeData somedata = someOtherNestFrag.getSomeData();
// it can be a string, or int, or some custom java object.
}
}
}
Add Tag when you do fragment transaction so you can look it up afterward to call its method. FragmentTransaction
This is the proper way to handle communication between fragment and nest fragment, it's almost the same for activity and fragment.
http://developer.android.com/guide/components/fragments.html#EventCallbacks
There is actually another official way, it's using activity result, but this one is good enough and common.
Instead of using interface, you can call the child fragment through below:
( (YourFragmentName) getParentFragment() ).yourMethodName();
The best way to pass data between fragments is using Interface. Here's what you need to do:
In you nested fragment:
public interface OnDataPass {
public void OnDataPass(int i);
}
OnDataPass dataPasser;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
dataPasser = (OnDataPass) a;
}
public void passData(int i) {
dataPasser.OnDataPass(i);
}
In your parent fragment:
public class Fragment_Parent extends Fragment implements OnDataPass {
...
#Override
public void OnDataPass(int i) {
this.input = i;
}
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("0");
((Fragment_Fr1) fragment).passData();
}
}
}
You can use share data between fragments.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
model.getSelected().observe(this, item -> {
// Update the UI.
});
}
}
More Info ViewModel Architecture
You can use getChildFragmentManager() and find nested fragments, get them and run some methods to retrieve input values
Check for instanceOf before getting parent fragment which is better:
if (getParentFragment() instanceof ParentFragmentName) {
getParentFragment().Your_parent_fragment_method();
}
Passing data between fragments can be done with FragmentManager. Starting with Fragment 1.3.0-alpha04, we can use setFragmentResultListener() and setFragmentResult() API to share data between fragments.
Official Documentation
Too late to ans bt i can suggest create EditText object in child fragment
EditText tx;
in Oncreateview Initialize it. then create another class for bridge like
public class bridge{
public static EditText text = null;
}
Now in parent fragment get its refrence.
EditText childedtx = bridge.text;
now on click method get value
onclick(view v){
childedtx.getText().tostring();
}
Tested in my project and its work like charm.
i have a problem with my three fragments application when i go to pass data between them.
I use an interface to pass the values, viewpager for the fragments and i keep the fragments on a list in the mainActivity.java.The problem seems to be the instance of the fragments i guess.
On my mainFragment (fragment1.java)i have two buttons, one for sending data to the 2nd fragment and one to send data to 3rd fragment.
The application works, and the data are shown on the second fragment when i press the button.
I get an exception if i press the second button to send the data to the third fragment.
The data are transfered to the 3rd fragment as they should be, but i get an exception if press the second button before i go to the second fragment and return to the first again.
I dont know if i make myself clear, but it seems that is an instance error although frag1 and frag2 have the same code.
here is my code:
mainactivity.java
public class MainActivity extends FragmentActivity
implements ICommunicator{
private String Importeddata;
private PagerAdapter mPagerAdapter;
private List<Fragment> fragments;
private ViewPager mpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
initialisePaging();
}
private void initialisePaging() {
// TODO Auto-generated method stub
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
mpager = (ViewPager)findViewById(R.id.viewpager);
mpager.setAdapter(mPagerAdapter);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
//Interface method implementation
public void respond(String data,int frItem) {
// TODO Auto-generated method stub
switch(frItem)
{
case 1:
/*
* THIS WAY WORKS 1
* Fragment2 fr2 = (Fragment2)fragments.get(1);
Toast.makeText(this, "you passed values"+data, Toast.LENGTH_SHORT).show();
System.out.println("you passed values"+data);
fr2.changeData(data);*/
/* THIS WAY WORKS 2
* Fragment2 fr2=(Fragment2)getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.viewpager+":1");
fr2.changeData(data);
*/
/* THIS WAY WORKS 3
*
*/
Fragment2 fr2=(Fragment2) mPagerAdapter.instantiateItem(mpager, 1);
fr2.changeData(data);
break;
case 2:
/*
* 1st way works, only if i first go to fragment 2 and return to firstfragment*/
/*otherwise i get a nullpointer EXCEPTION */
/*Fragment3 fr3 = (Fragment3)fragments.get(2);
Toast.makeText(this, "you passed values"+data, Toast.LENGTH_SHORT).show();
System.out.println("you passed values"+data);
fr3.changeData(data);*/
/*2nd way works, only if i first go to fragment 2 and return to firstfragment*/
/*otherwise i get a nullpointer EXCEPTION */
Fragment3 fr3=(Fragment3)getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.viewpager+":2");
fr3.changeData(data);
}
}
}
BELOW IS THE FRAGMENT1.JAVA which it has the two buttons
public class Fragment1 extends Fragment{
Button btn1;
Button btn2;
ICommunicator icommunicator;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e(getTag(), "onActivityCreated 1");
icommunicator = (ICommunicator) getActivity();
btn1 = (Button) getActivity().findViewById(R.id.Btn_Send);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "you pressed the button", Toast.LENGTH_LONG).show();
icommunicator.respond("hello from Fragment 1",1);
}
});
btn2 = (Button)getActivity().findViewById(R.id.Btn_Send2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "you pressed button 2", Toast.LENGTH_SHORT).show();
icommunicator.respond("hello from fragment1 fragment 2",2);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.e(getTag(), "onAttach 1");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e(getTag(), "onDestroy 1");
}
#Override
public void onPause() {
super.onPause();
Log.e(getTag(), "onPause 1");
}
#Override
public void onResume() {
super.onResume();
Log.e(getTag(), "onResume 1");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e(getTag(), "onCreateView 1");
if (container == null){
return null;
}
return inflater.inflate(R.layout.fragment1_layout,
container,false);
}
}
**below is the fragment2.java, the fragment that i send the btn1 message**
public class Fragment2 extends Fragment{
private String data;
private TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e(getTag(), "onCreateView 2");
txt = (TextView) getActivity().findViewById(R.id.txt_importData);
if (container == null){
return null;
}
return inflater.inflate(R.layout.fragment2_layout,
container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e(getTag(), "onActivityCreated 2");
txt = (TextView) getActivity().findViewById(R.id.txt_importData);
if (this.data == null)
txt.setText("i wait value....");
else
txt.setText(this.data);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.e(getTag(), "onAttach 2");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e(getTag(), "onDestroy 2");
}
#Override
public void onPause() {
super.onPause();
Log.e(getTag(), "onPause 2");
}
#Override
public void onResume() {
super.onResume();
Log.e(getTag(), "onResume 2");
}
public void changeData(String importdata){
this.data = importdata;
txt.setText(importdata);
}
}
below is the fragment3.java, the fragment that i send the btn2 message
the data are sent to the fragment3.java , so far so good, but i get a nullpointer exception unless i have gone to the second fragment first and return to the first fragment and after that i press the second button, it seems that is something wrong with the view instance of the fragment.
public class Fragment3 extends Fragment{
private String data;
private TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e(getTag(), "onCreateView 3");
txt = (TextView) getActivity().findViewById(R.id.txt_fragment3);
if (container == null){
return null;
}
return inflater.inflate(R.layout.fragment3_layout,
container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt_fragment3);
Log.e(getTag(), "onActivityCreated 3");
if (this.data == null)
txt.setText("i wait value....");
else
txt.setText(this.data);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.e(getTag(), "onAttach 3");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e(getTag(), "onDestroy 3");
}
#Override
public void onPause() {
super.onPause();
Log.e(getTag(), "onPause 3");
}
#Override
public void onResume() {
super.onResume();
Log.e(getTag(), "onResume 3");
}
public void changeData(String importdata){
this.data = importdata;
txt.setText(importdata);
}
}
if anyone can help me or tell his opinion i would appreciate it.
i need interface to communicate through fragments , that is the way fragments interact with each other, in your answer you suggest to pass the data from inside the clickListener if i am not mistake.
as for the setoffscreenPageLimit , can you tell me where i tell the code to cashe three pages or is it the way viewpager works to cache by default just three pages?
I added :
mpager.setOffscreenPageLimit(3);
and it works!
thank you.
It only caches 3 pages. Itself, page on right and on left. Add this:
mpager.setOffscreenPageLimit(3); // You have 3 fragments
And you can just do this, instead of doing all of that:
btn1 = (Button) getActivity().findViewById(R.id.Btn_Send);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView txt = (TextView) getActivity().findViewById(R.id.txt_importData);
txt.setText("whatever you want");
}
});
btn2 = (Button)getActivity().findViewById(R.id.Btn_Send2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView txt = (TextView) getActivity().findViewById(R.id.txt_fragment3);
txt.setText("whatever you want");
}
})