android fragment中EditText长按和点击无效的解决方案

本文介绍了一个凡人类聊天项目中遇到的问题:EditText组件在长按时无法弹出复制和删除菜单。通过设置XML文件中根节点的属性android:descendantFocusability=beforeDescendants成功解决了这一难题。

最近在做一个凡人类的聊天项目,有一个功能就是长按文本弹出一个popupwindow,有复制和删除的功能,但是半天发现EditText长按都没效果,查询了半天发现有一个属性

android:descendantFocusability="beforeDescendants"


把这个属性放在xml中的根目录下就解决了.在这记录下.


目前代码如下:package com.example.bus.ui.home; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.example.bus.MainActivity; import com.example.bus.RealTimePoiSuggestHelper; import com.example.bus.SearchResultActivity; import com.example.bus.databinding.FragmentHomeBinding; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private HomeViewModel homeViewModel; private static final int TIPS_DELAY = 300; // 防抖延迟 private Handler handler = new Handler(Looper.getMainLooper()); private Runnable pendingRequest; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); // 初始化 ViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); homeViewModel.getText().observe(getViewLifecycleOwner(), text -> { binding.textHome.setText(text); }); setupSearchSuggestion(); setupSearchAction(); setupSearchBoxWithPermissionControl(); return root; } private void setupSearchBoxWithPermissionControl() { binding.homeInput.setOnClickListener(v -> { MainActivity activity = (MainActivity) requireActivity(); activity.ensureFineLocationPermission(() -> { // 权限已获得,现在才允许 EditText 获取焦点并弹出软键盘 binding.homeInput.post(() -> { binding.homeInput.setFocusableInTouchMode(true); binding.homeInput.requestFocus(); InputMethodManager imm = (InputMethodManager) requireContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.showSoftInput(binding.homeInput, InputMethodManager.SHOW_IMPLICIT); } }); }); }); } /** * 设置输入建议功能(suggestion) */ private void setupSearchSuggestion() { // 创建建议助手 RealTimePoiSuggestHelper suggestHelper = new RealTimePoiSuggestHelper(requireContext()); suggestHelper.setCurrentCity("全国"); // 可改为动态城市 suggestHelper.setCallback(suggestions -> { if (suggestions.length > 0) { ArrayAdapter<String> adapter = new ArrayAdapter<>( requireContext(), android.R.layout.simple_dropdown_item_1line, suggestions ) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); // 👉 添加点击事件 view.setOnClickListener(v -> { String selectedText = getItem(position); if (selectedText != null && !selectedText.isEmpty()) { binding.homeInput.setText(selectedText); binding.homeInput.clearFocus(); // 隐藏软键盘 InputMethodManager imm = (InputMethodManager) requireContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(binding.homeInput.getWindowToken(), 0); } // 直接触发搜索(跳转到 SearchResultActivity) performSearch(); } }); return view; } }; // 主线程更新 UI new Handler(Looper.getMainLooper()).post(() -> { binding.homeInput.setAdapter(adapter); if (requireActivity().getCurrentFocus() == binding.homeInput) { binding.homeInput.showDropDown(); } }); } else { new Handler(Looper.getMainLooper()).post(() -> binding.homeInput.setAdapter(null) ); } }); // 防抖控制 handler = new Handler(Looper.getMainLooper()); pendingRequest = null; binding.homeInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (pendingRequest != null) { handler.removeCallbacks(pendingRequest); } if (s.length() == 0) { binding.homeInput.setAdapter(null); return; } boolean hasPermission = requireContext().checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED; if (!hasPermission) { // 没有权限 → 不请求建议,也不显示任何提示 binding.homeInput.setAdapter(null); return; } pendingRequest = () -> suggestHelper.requestSuggestions(s.toString()); handler.postDelayed(pendingRequest, TIPS_DELAY); } @Override public void afterTextChanged(Editable s) {} }); } /** * 设置搜索动作:回车 & 按钮点击 */ private void setupSearchAction() { // 回车搜索 binding.homeInput.setOnEditorActionListener((v, actionId, event) -> { if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_SEARCH) { performSearch(); return true; } return false; }); // 搜索按钮点击 binding.homeSearch.setOnClickListener(v -> performSearch()); } private void performSearch() { String keyword = binding.homeInput.getText().toString().trim(); if (keyword.isEmpty()) { Toast.makeText(requireContext(), "请输入关键词", Toast.LENGTH_SHORT).show(); return; } MainActivity activity = (MainActivity) requireActivity(); activity.ensureFineLocationPermission(() -> { Intent intent = new Intent(requireContext(), SearchResultActivity.class); intent.putExtra("keyword", keyword); startActivity(intent); }); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; // 清理防抖任务 if (handler != null) { handler.removeCallbacksAndMessages(null); } } } 经过调试,点击搜索框是能够弹出提示了,但是没有同意权限他却依然可以在搜索框输入内容
最新发布
12-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值