简体   繁体   English

OnClickListener 在片段中不起作用

[英]OnClickListener doesn't work in a fragment

I have here a problem with the onClicklistener method in a fragment.我在片段中的 onClicklistener 方法有问题。 If I click on the button nothing happens and I don't know why.如果我点击按钮,什么也没有发生,我不知道为什么。 No error and no output.没有错误,也没有 output。 I've tried to implements the OnClickListener or set a (Button) before the view.findViewById(R.id.button);我试图在view.findViewById(R.id.button);之前实现 OnClickListener 或设置一个(Button) ); but nothing helps.但没有任何帮助。 I've seen much questions here in Stack Overflow about this problem but no solution from there helps me:/我在 Stack Overflow 中看到了很多关于这个问题的问题,但没有任何解决方案可以帮助我:/

Do you have any ideas?你有什么想法? Thank You!谢谢你!

package com.christoph.myapplication.ui.home;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.christoph.myapplication.R;

public class HomeFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_home, container, false);

        final Button button= view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button.setBackgroundColor(Color.RED);
                System.out.println("Hallo");
            }
        });
        return view;
    }
}

You can add click listener rather in onViewCreated function.您可以在 onViewCreated function 中添加点击监听器。 Try it and let me know if it works.试试看,让我知道它是否有效。 Check android fragment lifecycles documentation for more info.查看 android 片段生命周期文档以获取更多信息。

Cheers干杯

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

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