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

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

问题描述

我第一次在片段中工作......在主要活动中,我有一个 spinnerListner 并且随着项目在微调器中的变化,在片段容器中......片段相应地发生变化,我刚刚在 fragment.xml 中创建了一些复选框文件...我只想在每次注册点击时为每个选中的复选框发布和存储一个不同的值NameoftheCheckbox",并为每个未选中的复选框(甚至来自未显示在容器中的片段)发布另一个值,例如Null".就像我试图在我的主要活动中通过 RegisterUser 函数存储名称和 pin 的方式......

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

我的主要活动

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

    }
}

我的片段活动

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

编译'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.

公共类事件{公共静态类 RegisterEvent {公共注册事件(){}}}

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

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

公共类 GlobalBus {私有静态总线 sBus;公共静态总线 getBus(){如果(sBus == null)sBus = 新总线();返回sBus;}}

点击注册按钮时使用 otto eventbus 库发布 RegisterEvent 事件.

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

registerBtn.setOnClickListener(new View.OnClickListener() {@覆盖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);

然后,在 Fragment 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.

@Subscribepublic void showMessage(Events.RegisterEvent events) {///这里,你需要检查复选框是否被选中.根据那个向服务器发送消息.对每个复选框重复相同的过程.}

在每个片段中重复与第 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天全站免登陆