英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论