首页 > 解决方案 > onclick 侦听器在片段中不起作用

问题描述

当我单击应用程序中的按钮时,我在按钮上实现了一个 onclicklistener 以打开画廊,没有任何反应

代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_statusfragment,container,false);
    imageView = view.findViewById(R.id.imageView);
    button = (Button)view.findViewById(R.id.button2);
    textView = view.findViewById(R.id.textView);
    view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(),"Upload screenshot",Toast.LENGTH_LONG).show();
            if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                requestPermissions(
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        2000);
            }else {
                Toast.makeText(getActivity(), "Choose Screenshot", Toast.LENGTH_LONG).show();
                imageView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                textView.setVisibility(View.VISIBLE);
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivityForResult(intent,1000);
                }
            }
        }
    });
// Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_statusfragment, container, false);
}

它也不显示 Toast 消息

标签: javaandroid-studioonclicklistenerandroid-button

解决方案


而不是return inflater.inflate(R.layout.fragment_statusfragment, container, false);return view;


推荐阅读