0

I'm using 2 EditText next to each other, the left one gains focus on the fragment startup, I want to give the right one focus I've tried to call requestFocus() on the right EditText but it's not working

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sandwich_fragment,container, false);

        sandwichNameEditText = view.findViewById(R.id.sandwich_name_edit_text);
        sandwichPriceEditText = view.findViewById(R.id.sandwich_price_edit_text);
        insertSandwichImageView = view.findViewById(R.id.insert_sandwich_btn);
        sandwichListView = view.findViewById(R.id.sandwich_list);

        dbHandler = new DBHandler(getContext(),null);
        sandwichArrayList = dbHandler.getSandwiches();

        final SandwichListAdapter adpater = new SandwichListAdapter(getContext(),
                R.layout.sandwich_item, sandwichArrayList);

            sandwichListView.setAdapter(adpater);


        insertSandwichImageView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(sandwichNameEditText.getText().toString().equals("") || sandwichPriceEditText.getText().toString().equals("")){
                    Toast.makeText(getContext(),"No empty strings.", Toast.LENGTH_SHORT).show();
                    return;
                }
                Sandwich sandwich = new Sandwich(sandwichNameEditText.getText().toString(),
                        Double.parseDouble(sandwichPriceEditText.getText().toString()));
                dbHandler.addSandwich(sandwich);
                adpater.add(sandwich);
                sandwichNameEditText.setText("");
                sandwichPriceEditText.setText("");
                sandwichNameEditText.requestFocus(); // working here

            }
        });
        sandwichNameEditText.requestFocus(); // not working here
        return view;
Ahmed Nabil
  • 581
  • 1
  • 7
  • 26

1 Answers1

1

Try to call requestFocus in the onViewCreated method.

The request for focus is something you should do once your View is created.

You can find some insights about the difference between onCreateView and onViewCreated methods for a Fragment here.

That said, you should move your view elements initialisations in the onViewCreated as well, since they're something you want to do after the view is created and not while it's being created. Just leave the inflate logic there, and do the other logic once the View is there.

magicleon94
  • 4,887
  • 2
  • 24
  • 53