首页 > 解决方案 > 控制片段中的按钮

问题描述

我想从片段活动中的片段 xml 文件中控制按钮。在其他活动中,我们可以通过 findviewbyid 方法轻松控制我们的按钮,然后我们可以应用 setonclicklistener。但是在片段中,我如何访问按钮并应用 onclicklistener 方法。 我的片段.java

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.LinearLayout;


    /**
     * A simple {@link Fragment} subclass.
     */
    public class QuoteTypeFragment extends Fragment {


        public QuoteTypeFragment() {
            // Required empty public constructor
        }

        LinearLayout  typeOne, typeTwo, typeThree, typeFour;

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

    }

我的片段.xml

 <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#3f525e"
        tools:context=".QuoteTypeFragment">



    <Button
        android:id="@+id/submitbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit"/>

    </FrameLayout>

所以这里我要控制fragment.java中的提交按钮。如何通过 findviewbyid 或 findfragmentbyid 访问按钮。在 fragment.java 中,我在哪里使用该代码来访问提交按钮。

标签: javaandroidandroid-fragments

解决方案


在 OnCreateView

    Button button;

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

            button = vv.findViewById(R.id.submitbutton);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });

             return vv;
            }

推荐阅读