android-fragments 自动聚焦位于RecyclerView适配器内部EditText

5rgfhyps  于 2022-11-14  发布在  Android
关注(0)|答案(2)|浏览(149)

我有一个Fragment,它有一个RecyclerView。这个RecyclerView有一个头适配器,它包含一个EditText。
当Fragment进入视图时,我希望EditText自动聚焦(即自动显示键盘)。
我该怎么做?
碎片:

public class My Fragment extends Fragment {

    private LinearLayoutManager layoutManager;

    private FeedRecyclerView recyclerView;

    private PostAdapter postAdapter;

    private ConcatAdapter concatAdapter;

    private HeaderAdapter headerAdapter;

    private List<Post> postData = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.my_fragment, parent, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        recyclerView = view.findViewById(R.id.recycler_view);

        layoutManager = new FeedLinearLayoutManager(getContext());

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        // This is the adapter that contains the EditText
        headerAdapter = new HeaderAdapter(getContext());

        postAdapter = new PostAdapter(getContext(), postData, layoutManager);

        concatAdapter = new ConcatAdapter();
        recyclerView.setAdapter(concatAdapter);

        concatAdapter.addAdapter(searchHeaderAdapter);
    }
}

适配器类HeaderAdapter:

public class HeaderAdapter extends RecyclerView.Adapter<HeaderAdapter.ViewHolder> {

    private Context context;

    public HeaderAdapter(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_header, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //
    }

    @Override
    public long getItemId(int position) {
        return 1;
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public EditText myEditText;

        public ViewHolder(View v) {
            super(v);

            myEditText = v.findViewById(R.id.my_edit_text);
        }
    }

}

如您所见,我的RecyclerView的适配器HeaderAdapter具有EditText。当显示Fragment时,我希望自动聚焦此EditText。
我该怎么做?
谢谢你!

nlejzf6q

nlejzf6q1#

将这一行myEditText.requestFocus()添加到页眉视图保持器的init中

init {
    myEditText = v.findViewById(R.id.my_edit_text)
    myEditText.requestFocus()
}
gudnpqoy

gudnpqoy2#

试试这个

@Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.myEditText.requestFocus();
        
 ((InputMethodManager)holder.itemView.context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(holder.myEditText, 0);
        }

相关问题