OnClickListener在片段中不起作用。

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

OnClickListener doesn't work in a fragment

问题

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

  1. package com.christoph.myapplication.ui.home;
  2. import android.graphics.Color;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.widget.Button;
  8. import androidx.annotation.NonNull;
  9. import androidx.fragment.app.Fragment;
  10. import com.christoph.myapplication.R;
  11. public class HomeFragment extends Fragment {
  12. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  13. final View view = inflater.inflate(R.layout.fragment_home, container, false);
  14. final Button button = view.findViewById(R.id.button);
  15. button.setOnClickListener(new View.OnClickListener() {
  16. @Override
  17. public void onClick(View view) {
  18. button.setBackgroundColor(Color.RED);
  19. System.out.println("Hallo");
  20. }
  21. });
  22. return view;
  23. }
  24. }
英文:

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!

  1. package com.christoph.myapplication.ui.home;
  2. import android.graphics.Color;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.widget.Button;
  8. import androidx.annotation.NonNull;
  9. import androidx.fragment.app.Fragment;
  10. import com.christoph.myapplication.R;
  11. public class HomeFragment extends Fragment {
  12. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  13. final View view = inflater.inflate(R.layout.fragment_home, container, false);
  14. final Button button= view.findViewById(R.id.button);
  15. button.setOnClickListener(new View.OnClickListener() {
  16. @Override
  17. public void onClick(View view) {
  18. button.setBackgroundColor(Color.RED);
  19. System.out.println("Hallo");
  20. }
  21. });
  22. return view;
  23. }
  24. }

答案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:

确定