如何在片段中使用OnClickListener

问题描述 投票:0回答:1

这是我的代码。我还在学习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>

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

        }
    }
}
java android android-fragments onclick onclicklistener
1个回答
0
投票
btn2 = (Button)CView.findViewById(R.id.btnCourse); final TextView txt = (TextView)CView.findViewById(R.id.textView2); btn2.setOnClickListener(this)
© www.soinside.com 2019 - 2024. All rights reserved.