-1

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;
    }
}

enter image description here

enter image description here

  • Set checkbox item static Not recommended always or you could set a interface and listner – g7pro Mar 24 '17 at 10:11
  • @GIBINTHOMAS didn't get you, can you show me editing my code? –  Mar 24 '17 at 10:13
  • where exactly is the checkbox in the fragment? – g7pro Mar 24 '17 at 10:15
  • in both blank fragment and blank fragment 2 – g7pro Mar 24 '17 at 10:15
  • @GIBINTHOMAS yes in both fragments and in fragment container it changes according to spinner item selection. –  Mar 24 '17 at 10:18
  • 1
    not recommended in all cases but here to get it solved use a static object for the checkbox in both fragment initialisation and check is checked in both checkboxed in the submit button? – g7pro Mar 24 '17 at 10:22
  • @GIBINTHOMAS can you show me editing my code? if possible... Thanks –  Mar 24 '17 at 10:24
  • @GT Can you help me with [this question](http://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of)? –  Mar 31 '17 at 12:03
  • Just some logic not the complete code i have written If you couldn't meet need just comment below cheers happy coding – g7pro Mar 31 '17 at 12:22

5 Answers5

2

You can use interface to communicate back to MainActivity.

  1. Create a interface and implement it on MainActivity.
  2. Pass the implemented interface to fragment and store it in the fragment
  3. 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.
  4. 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);
Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50
  • Hi! can you show me editing my code? because i am totally new to android. –  Mar 24 '17 at 10:16
  • Added some code . Please check and also search internet for Interface and how it work. – Abu Yousuf Mar 24 '17 at 10:40
  • Can you help me with [this question](http://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of)? –  Mar 31 '17 at 12:02
2

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
    }
});

...
  • what if i already have implemented a listener on my MainActivity like "public class MainActivity extends AppCompatActivity implements View.OnClickListener"? you should check [this](http://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of?noredirect=1#comment73171661_43042631), if you can answer this. it would be great. –  Mar 28 '17 at 11:47
  • Can you help me with [this](http://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of/43086777?noredirect=1#comment73255974_43086777)? –  Mar 31 '17 at 11:46
0

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.

Community
  • 1
  • 1
midhunhk
  • 5,560
  • 7
  • 52
  • 83
  • You can implement CheckboxStatusObserver in fragments right? – g7pro Mar 24 '17 at 10:27
  • then where is the code for tosting status of checkbox checked or not checked –  Mar 24 '17 at 10:31
  • Kindly read the links given at the end. Parent Activity would implement the interface and will get notified by the child Fragment. – midhunhk Mar 24 '17 at 10:31
  • In checkBoxChanged() method of MainActivity as in the updated code. – midhunhk Mar 24 '17 at 10:34
  • @midhunhk Can you help me with [this question](http://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of)? –  Mar 31 '17 at 12:00
0

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
      }
    }
Rajesh
  • 2,618
  • 19
  • 25
0

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;
    }

}
g7pro
  • 817
  • 1
  • 6
  • 11
  • My guess is you got something wrong in the calling of fragment from activity and not the checkbox selction right .If otherwise note down i will make the required changes – g7pro Mar 31 '17 at 12:24
  • can you answer help me with this [question](http://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of/43086777?noredirect=1#comment73255974_43086777)? –  Mar 31 '17 at 12:37
  • Try this same logic there – g7pro Mar 31 '17 at 12:43
  • you didn't get it i guess, buddy... I want every checkboxes to respond at the same time... even if a fragment isn't showing it need to post the checkbox value like "N.A" please check and read [This Question](http://stackoverflow.com/questions/43155452/how-to-post-using-checkbox-inside-fragments-to-server-through-volley-registra) carefully. –  Apr 02 '17 at 07:05