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.
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 have a MainActivity and a HomeTabs with three tabs (A B C), i set a refresh on tab C .
My structure is when i trigger onRefresh on tab C , i will switch to MainActivity
and load the data again to show the HomeTabs.
My problem is when i click back for finish(); , the layout will show tab C.
I try to finish the Fragment use like:
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
or
((MainActivity)getActivity()).removeFragment(getActivity());
Both of them are no working , when i click back , i still can't finish the app immediately.
Some one can teach me what step i miss it , that would be appreciated.
My HomeTabs extends Fragment it use ViewPager and TabLayout add three tabs
MainActivity:
public class MainActivity extends AppCompatActivity {
private FrameLayout frameLayout;
private Toolbar toolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
// Load the main Fragment
if (savedInstanceState == null) {
switchFragment(HomeTabs.newInstance());
}
//take the onRefresh data,send data to HomeTabs and open tab C
if (getIntent().hasExtra("refresh")) {
boolean isRefresh = getIntent().getExtras().getBoolean("refresh");
if (isRefresh) {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", isRefresh);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
}
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// I try to finsh my tab C , it's no working
public void removeFragment(Activity activity) {
activity.onBackPressed();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new DialogHandler(this).quickDialog(
getResources().getString(R.string.quick),
getResources().getString(R.string.confirm),
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// If i onRefrsh three times , i will finsh three times... here is my issue.
finish();
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
return super.onKeyDown(keyCode, event);
}
}
Here is my tab C Fragment refresh call back method:
public class MyLineChart extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_line_chart, container, false);
//.....................
return view;
}
#Override
public void onRefresh() {
refreshLayout.setRefreshing(false);
// Both of them are no working.
//((MainActivity)getActivity()).removeFragment(getActivity());
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
Intent intent = new Intent(getActivity(),MainActivity.class);
intent.putExtra("refresh", true);
startActivity(intent);
}
Finally my HomeTabs Fragment take the date and show tab C:
Bundle bundle = getArguments();
if (bundle != null) {
boolean isRefresh = bundle.getBoolean("refresh");
if (isRefresh) {
//tab C position is 2
tabLayout.getTabAt(2).select();
}
}
Try this solution to add below code when you are starting activity again on Refresh click:-
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
OR
Update your MainActivity.java
1) Add function in MainActivity
public void refreshFragment() {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", isRefresh);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
Now Call that from Fragment Tab C just replacing startActivity(refresh) code:
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.refreshFragment();
you can add a listener in your fragment that can trigger a function in your parent activity
which means you need to add an interface in your fragmentC code
public class MyLineChart extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private MyLineChartListener fragmentListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_line_chart, container, false);
//.....................
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyLineChartListener) {
fragmentListener = (MyLineChartListener) context;
} else {
// throw an error
}
}
#Override
public void onRefresh() {
refreshLayout.setRefreshing(false);
// Both of them are no working.
//((MainActivity)getActivity()).removeFragment(getActivity());
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
fragmentListener.onSettingRefresh();
}
public interface MyLineChartListener {
void onSettingRefresh();
}
}
then you need to implement the listener in the MainActivity code as follows
public class MainActivity extends AppCompatActivity implements MyLineChart.MyLineChartListener {
private FrameLayout frameLayout;
private Toolbar toolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
// Load the main Fragment
if (savedInstanceState == null) {
switchFragment(HomeTabs.newInstance());
}
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// I try to finsh my tab C , it's no working
public void removeFragment(Activity activity) {
activity.onBackPressed();
}
// this function will be called when the fragment is refreshed
#Override
public void onSettingRefresh() {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", true);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new DialogHandler(this).quickDialog(
getResources().getString(R.string.quick),
getResources().getString(R.string.confirm),
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// If i onRefrsh three times , i will finsh three times... here is my issue.
finish();
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
return super.onKeyDown(keyCode, event);
}
}
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;
}
}
From all the searches I have found on SO stating that you should save your instance state in the #Override public void onSaveInstanceState(Bundle outState)
However This is tightly coupled with the activities lifestyle.
How can I save the state of my listview in a fragment that gets swapped out with another fragment.
I have one main activity which all the fragments are loaded into.
I have tried this so far:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save adapter data so that when the fragment is returned to it can be resused.
ArrayList<CategoryMobileDto> categories = new ArrayList<CategoryMobileDto>();
for(int i=0; i < adapter.getCount();i++)
{
categories.add(adapter.getItem(i));
}
String persistData = new Gson().toJson(categories);
outState.putString("Categories", persistData);
}
and then in my OnCreate();
if(savedInstanceState!=null)
{
String data =savedInstanceState.getString("Categories");
Type collectionType = new TypeToken<ArrayList<CategoryMobileDto>>() {
}.getType();
adapter.addAll(gson.<Collection<CategoryMobileDto>>fromJson(data, collectionType));
adapter.notifyDataSetChanged();
}else{
// Make request to server
}
however savedInstanceState is always null. But this makes sense as my activity is not being destroyed and recreated.
This is how I transition from one fragment to another:
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment, "ProductListFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Is there a way i can save the state of my listview when the fragment is removed and then restore it again when the fragment is popped from the back-stack?
Move this code from onCreate() to onActivityCreated() of Fragment
if(savedInstanceState!=null)
{
String data =savedInstanceState.getString("Categories");
Type collectionType = new TypeToken<ArrayList<CategoryMobileDto>>() {
}.getType();
adapter.addAll(gson.<Collection<CategoryMobileDto>>fromJson(data, collectionType));
adapter.notifyDataSetChanged();
}else{
// Make request to server
}
If you have any query please let me know.
You can use the Arguments with the Fragment(Only if you have the data to show in fragment before the fragment is loaded means attached). You can setArguments to a fragment which will be persisted when you go to another fragment by fragment transaction and when you come back, load the fragment from the getArguments function.
public void setArguments (Bundle args)
Added in API level 11
Supply the construction arguments for this fragment. This can only be called before the fragment has been attached to its activity; that is, you should call it immediately after constructing the fragment. The arguments supplied here will be retained across fragment destroy and creation.
public final Bundle getArguments ()
Added in API level 11
Return the arguments supplied when the fragment was instantiated, if any.
Please find the sample code below for passing data between fragments :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/flContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
MainActivity.java
public class MainActivity extends Activity implements IFragContainer {
private static final String FRAG_TAG = "FragTag";
private FragBase mFrag;
private String dataToBePassedBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
changeFragment(FragA.class, "Data to Frag A");
}
#Override
public void changeFragment(Class<? extends FragBase> fragClass, String data) {
try {
FragmentTransaction ft = getFragmentManager().beginTransaction();
mFrag = fragClass.newInstance();
Bundle args = new Bundle();
args.putString("DATA", data);
mFrag.setArguments(args);
ft.replace(R.id.flContainer, mFrag, FRAG_TAG);
ft.addToBackStack(mFrag.toString());
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
dataToBePassedBack = mFrag.getDataToPassBack();
FragmentManager mgr = getFragmentManager();
mgr.executePendingTransactions();
boolean doCheckAndExit = true;
for (int i = mgr.getBackStackEntryCount() - 1; i > 0; i--) {
BackStackEntry entry = mgr.getBackStackEntryAt(i);
if (!TextUtils.isEmpty(entry.getName())) {
mgr.popBackStackImmediate(entry.getId(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
doCheckAndExit = false;
break;
}
}
if (doCheckAndExit) {
finish();
} else {
mFrag = (FragBase) mgr.findFragmentByTag(FRAG_TAG);
}
}
#Override
public String getDataToBePassedBack() {
return dataToBePassedBack;
}
}
IFragContainer.java
public interface IFragContainer {
void changeFragment(Class<? extends FragBase> fragClass, String data);
String getDataToBePassedBack();
}
FragBase.java
public abstract class FragBase extends Fragment {
public String getDataToPassBack(){
return null;
}
}
FragA.java
public class FragA extends FragBase {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button btn = new Button(getActivity());
final IFragContainer fragContainer = (IFragContainer) getActivity();
if (TextUtils.isEmpty(fragContainer.getDataToBePassedBack())) {
btn.setText(getArguments().getString("DATA"));
} else {
btn.setText(fragContainer.getDataToBePassedBack());
}
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fragContainer.changeFragment(FragB.class, "Data to Frag B");
}
});
return btn;
}
}
FragB.java
public class FragB extends FragBase {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button btn = new Button(getActivity());
btn.setText(getArguments().getString("DATA"));
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
return btn;
}
#Override
public String getDataToPassBack() {
return "Data from Frag B to A";
}
}
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
}
}
}