I have a checkbox inside a fragment and i want it to post some data on click of a register button this button is inside my main activity?

强颜欢笑 提交于 2020-01-11 13:14:09

问题


I am working for the 1st time in fragment...in main activity i have a spinnerListner and as the item changes in spinner, in fragment container... fragments changes accordingly and i have just created some checkboxes in fragment.xml files... i just want to post and store a different value "NameoftheCheckbox" for every checked checkbox and another valuelike"Null" for every unchecked checkbox(even from the fragments which is not showing in container) on every registration click. like the way i am trying to store name and pin through RegisterUser function in my main activity...

My MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_Name, et_Pin;
    private Button RegisterBTN;
    private ProgressDialog progressDialog;

    private CheckBox checka, checkb;

    private Spinner sDropdown;
    ArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_Name = (EditText)findViewById(R.id.etName);
        et_Pin = (EditText)findViewById(R.id.etPin);

        checka = (CheckBox)findViewById(R.id.checkBox_a);


        RegisterBTN = (Button)findViewById(R.id.btn_Reg);

        progressDialog = new ProgressDialog(this);
        //progressDialog.setMessage();

        adapter = ArrayAdapter.createFromResource(this, R.array.spinner_options, android.R.layout.simple_spinner_item);

        spinnerListner();

        RegisterBTN.setOnClickListener(this);


    }

    public void spinnerListner(){
        sDropdown = (Spinner)findViewById(R.id.spinner2);
        sDropdown.setAdapter(adapter);
        sDropdown.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, Info_frag.newInstance()).addToBackStack(null).commit();
                                break;
                            case 1:
                               getSupportFragmentManager().beginTransaction().replace(R.id.frag, Plumber_frag.newInstance()).addToBackStack(null).commit();
                                break;
                            case 2:
                                getSupportFragmentManager().beginTransaction().replace(R.id.frag, Painter_frag.newInstance()).addToBackStack(null).commit();
                                break;
                            case 3:
                                getSupportFragmentManager().beginTransaction().replace(R.id.frag, Electrician_frag.newInstance()).addToBackStack(null).commit();
                                //Toast.makeText(MainActivity.this,"F3", Toast.LENGTH_SHORT).show();
                                break;
                        }

                        /**
                         * TextView spinnerDailogText = (TextView)view;
                        Toast.makeText(MainActivity.this, "You selected:"+ spinnerDailogText.getText(), Toast.LENGTH_SHORT).show();*/
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                }
        );
    }


    private void registerUser(){
        final String name = et_Name.getText().toString().trim();
        final String pin = et_Pin.getText().toString().trim();

        progressDialog.setMessage("Registering please wait...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                Constants.REGISTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.hide();
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("reg_name", name);
                params.put("reg_pin", pin);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {

        if (v == RegisterBTN);
            registerUser();

    }
}

My FragmentActivity

public class Electrician_frag extends Fragment {

    public static Electrician_frag newInstance() {
        Electrician_frag fragment = new Electrician_frag();
        return fragment;
    }

    public Electrician_frag(){

    }

      @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootview = inflater.inflate(R.layout.fragment_electrician, container, false);
          return rootview;
    }

}

Another Fragment Activity

public class Painter_frag extends Fragment {

    public static Painter_frag newInstance(){
        Painter_frag fragment = new Painter_frag();
        return fragment;
    }

    public Painter_frag(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootview = inflater.inflate(R.layout.fragment_painter, container, false);
        return rootview;
    }
}

My PainterFragment.xml

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">

        <CheckBox
            android:id="@+id/checkBox_x"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="124dp"
            android:layout_marginStart="124dp"
            android:text="@string/a"
            android:textSize="20sp"
            android:textStyle="bold" />

        <CheckBox
            android:id="@+id/checkBox_y"
            style="@android:style/Widget.Holo.Light.CompoundButton.CheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="70dp"
            android:layout_marginStart="70dp"
            android:layout_toEndOf="@+id/checkBox_x"
            android:layout_toRightOf="@+id/checkBox_x"
            android:text="@string/b"
            android:textSize="20sp"
            android:textStyle="bold" />

    </RelativeLayout>
</FrameLayout>

回答1:


As far as i understood your question. We have following scenarios.
1. You have MainActivity.
2. In this MainActivity, you are trying to implement a registration form.
3. In registration Form, you have multiple fragments that contains checkboxes.
4. when you click on register button(inside MainActivity), you want to post some data that depends whether checkboxes are checked or not.

If this is the scenario, you can easily achieve the target using Otto event bus library or Guava event bus library. This way also help you to maintain the modularity of the app code.

I am giving a brief info how you can do it.

Follow below steps to get the solution.

  1. Add gradle into your project

    compile 'com.squareup:otto:1.3.8'

  2. Create a Events class in you project and create an event to post whenever REGISTER button is clicked. For example, your Events class will contain below code.

    public class Events { public static class RegisterEvent { public RegisterEvent() {} } }

  3. Create a GlobalBus class in your project so that you can access same bus throughout you application. Write below code into it.

    public class GlobalBus { private static Bus sBus; public static Bus getBus(){ if (sBus == null) sBus = new Bus(); return sBus; } }

  4. Post RegisterEvent event using otto eventbus library when REGISTER button is clicked.

    registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GlobalBus.getBus().post(new Events.RegisterEvent()); } });

  5. In Fragment A, You write code to subscribe to the otto eventbus as below.

    GlobalBus.getBus().register(this);

  6. In Fragment A, then, write a subscribe method to subscribe to the event(i.e. RegisterEvent) so that whenever this event is posted from MainActivity, you a get the notification and show the proper message(i.e. whether checkbox is checked or not). You can write subscribe method as below.

    @Subscribe public void showMessage(Events.RegisterEvent events) { /// Here, you need to check whether checkboxes are checked or not. Send message to the server depending on that. Repeat same process for every checkbox. }

  7. Repeat same process as step 4 and 5 in every fragment.

Note: Remember each fragment will receive notification when register button is clicked. Then, it will check checkboxes(whether checkboxes are checked or not) and send the request to server.

Note: if you want to know more about otto event bus library you can check https://tutorialwing.com/otto-event-bus-tutorial-example/
Also, If you want to use Guava eventbus, you can check https://tutorialwing.com/android-eventbus-library-example/
Both libraries has some pros and cons.



来源:https://stackoverflow.com/questions/43042631/i-have-a-checkbox-inside-a-fragment-and-i-want-it-to-post-some-data-on-click-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!