繁体   English   中英

如何在 Fragments 中使用 OnClickListener

[英]How use OnClickListener in Fragments

这是我的代码。 我还在学习android studio。 我想在单击按钮时显示祝酒词,但是当我运行应用程序并单击按钮时,它什么也不做。 (这是一个片段)。 有谁知道如何解决这一问题? 我尝试将“onClick”方法放在 xml( android:onClick="onClick" ) 中,然后我点击按钮后应用程序就崩溃了。

fragment_fragment_course.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragmentCourse">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Course"
        android:textSize="25sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnCourse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

片段课程.java

package com.example.sma;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;


public class fragmentCourse extends Fragment implements View.OnClickListener {

    Button btn2;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View CView = inflater.inflate(R.layout.fragment_fragment_course, container, false);

        btn2 = (Button)CView.findViewById(R.id.btnCourse);
        final TextView txt = (TextView)CView.findViewById(R.id.textView2);

        btn2.setOnClickListener(this);

        return CView;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btnCourse:
                Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
                break;

        }
    }
}

覆盖onViewCreated方法并将下面的代码移动到那里。 您无法访问片段的onCreateView中的视图。

btn2 = (Button)CView.findViewById(R.id.btnCourse);
final TextView txt = (TextView)CView.findViewById(R.id.textView2);
btn2.setOnClickListener(this)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM