猿问

控制片段中的按钮

我想在片段活动中控制片段 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 中,我在哪里使用该代码访问提交按钮。



隔江千里
浏览 142回答 3
3回答

Smart猫小萌

在 OnCreateView 中&nbsp; &nbsp; Button button;&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public View onCreateView(LayoutInflater inflater, ViewGroup container,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Inflate the layout for this fragment&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; button = vv.findViewById(R.id.submitbutton);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; button.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void onClick(View view) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return vv;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答