OnClickListener在片段中不起作用。

huangapple go评论77阅读模式
英文:

OnClickListener doesn't work in a fragment

问题

以下是你提供的代码的中文翻译:

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;
    }
}
英文:

I have here a problem with the onClicklistener method in a fragment. If I click on the button nothing happens and I don't know why. No error and no output.
I've tried to implements the OnClickListener or set a (Button) before the view.findViewById(R.id.button); but nothing helps.
I've seen much questions here in Stack Overflow about this problem but no solution from there helps me :/

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;
    }
}

答案1

得分: 1

你可以将点击监听器添加到onViewCreated函数中。试试看,然后告诉我是否有效。请查阅Android片段生命周期文档以获取更多信息。

祝好!

英文:

You can add click listener rather in onViewCreated function. Try it and let me know if it works. Check android fragment lifecycles documentation for more info.

Cheers

huangapple
  • 本文由 发表于 2020年7月26日 22:44:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63101667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定