我在片段中有一个复选框,我希望它在单击注册按钮时发布一些数据,这个按钮在我的主要活动中吗? [英] 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?

查看:71
本文介绍了我在片段中有一个复选框,我希望它在单击注册按钮时发布一些数据,这个按钮在我的主要活动中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在fragment中工作...在主要活动中,我有一个spinnerListner,随着Spinner中项目的变化,在fragment容器中... fragment相应地发生变化,而我刚刚在fragment.xml中创建了一些复选框文件...我只想在每次注册单击时为每个选中的复选框发布并存储一个不同的值"NameoftheCheckbox",为每个未选中的复选框存储另一个值,如"Null"(即使是未显示在容器中的片段).就像我尝试通过RegisterUser函数在我的主要活动中存储名称和固定密码的方式一样.

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...

我的MainActivity

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

    }
}

我的FragmentActivity

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

}

另一个片段活动

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

我的PainterFragment.xml

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.您拥有MainActivity.
2.在此MainActivity中,您正在尝试实施注册表格.
3.在注册表中,您有多个包含复选框的片段.
4.当您单击注册按钮(位于MainActivity内部)时,您要发布一些数据,该数据取决于是否选中了复选框.

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.

在这种情况下,您可以使用Otto事件总线库或Guava事件总线库轻松实现目标.这样还可以帮助您保持应用程序代码的模块化.

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. 在您的项目中添加gradle

  1. Add gradle into your project

compile 'com.squareup:otto:1.3.8'

在您的项目中创建一个事件类,并创建一个事件,只要单击注册"按钮即可发布.例如,您的Events类将包含以下代码.

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() {} } }

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

在项目中创建GlobalBus类,以便您可以在整个应用程序中访问同一总线.将下面的代码写入其中.

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

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

单击REGISTER按钮时,使用otto事件总线库发布RegisterEvent事件.

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

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

在片段A中,您编写代码以订阅otto事件总线,如下所示.

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

GlobalBus.getBus().register(this);

然后在片段A中编写一个订阅方法以订阅事件(即RegisterEvent),以便无论何时从MainActivity发布此事件,您都将获得通知并显示正确的消息(即,复选框是否为检查或不检查).您可以编写如下的订阅方法.

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

@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. }

在每个片段中重复与步骤4和5相同的过程.

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.

注意:如果您想了解更多关于otto事件总线库的信息,可以查看 https://tutorialwing.com/otto-event-bus-tutorial-example/
另外,如果您想使用Guava eventbus,则可以检查 https://tutorialwing.com/android-eventbus-library-example/
这两个库都有优点和缺点.

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.

这篇关于我在片段中有一个复选框,我希望它在单击注册按钮时发布一些数据,这个按钮在我的主要活动中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆