Profile Fragment中设置OnClickListener提示代码不可达问题求助
问题分析与解决方案
你遇到的代码不可达错误核心原因是:在onCreateView方法中,你在设置按钮点击监听器之前就执行了return root;,这会直接退出方法,导致后面的setOnClickListener代码永远不会被执行。
另外你的代码还有几个小问题需要修正:
de.hdodenhof.circleimageview.CircleImageView;这行缺少import关键字,会导致编译错误onActivityResult方法中,判断请求码时错误地使用了resultCode,应该用requestCode- 方法末尾的第二个
return root;完全多余,且同样处于不可达位置
修正后的完整代码
package com.example.stepapp.ui.profile; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.stepapp.R; import de.hdodenhof.circleimageview.CircleImageView; public class ProfileFragment extends Fragment { private Button ImCh; CircleImageView profile_image; private Button user; private TextView Username; private final int GALLERY_REQ_CODE=1000; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container != null) { container.removeAllViews(); } View root = inflater.inflate(R.layout.fragment_profile, container, false); ImCh =(Button) root.findViewById(R.id.fab); user=(Button) root.findViewById(R.id.EditName); profile_image =root.findViewById(R.id.profile_image); Username = root.findViewById(R.id.Username); Toast.makeText(getContext(), "testing the button " +String.valueOf(ImCh.getId()), Toast.LENGTH_SHORT).show(); // 将点击监听器设置放在return之前 ImCh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent iGallery = new Intent(Intent.ACTION_PICK); iGallery.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(iGallery,GALLERY_REQ_CODE); } }); user.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Username.setText(""); } }); // 最后再返回root视图 return root; } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // 修正请求码判断逻辑 if(resultCode == getActivity().RESULT_OK){ if(requestCode == GALLERY_REQ_CODE && data != null){ profile_image.setImageURI(data.getData()); } } } }
关键修正点说明
- 把
return root;移到所有视图初始化和监听器设置代码之后,确保这些代码能被执行 - 补全
CircleImageView的import语句 - 修正
onActivityResult中的判断条件,将resultCode==GALLERY_REQ_CODE改为requestCode==GALLERY_REQ_CODE,同时增加data != null的判断避免空指针异常 - 移除多余的第二个
return root;
内容的提问来源于stack exchange,提问作者Kaan
相关产品推荐
相关产品推荐

