Tuesday, 26 July 2022

Auto focus EditText that sits inside RecyclerView adapter

I've got a Fragment, which has a RecyclerView. This RecyclerView has a header adapter, which contains an EditText.

When the Fragment comes into view, I want the EditText to auto focus (i.e. show the keyboard automatically).

How would I do this?

The Fragment:

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);
    }
}

The adapter class, 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);
        }
    }

}

As you can see, my RecyclerView's adapter, HeaderAdapter, has the EditText. When the Fragment gets shown, I want to auto focus this EditText.

How would I do this?

Thank you



from Auto focus EditText that sits inside RecyclerView adapter

No comments:

Post a Comment