Focus EditText Android

1

How do I get focus on EditText but still with problems?

I'm doing an ordering system, I have 3 EditText (product, quantity and discount) and a Add button.

I need that when the user clicks the add button, the focus goes back to the product field, today the focus is going to a editText of listView (order items) that has just been added.

So if the user adds 30 products he has to scroll the screen up and focus on the product.

I'm using Android 4.1

Code (no onclick of the add button)

try{
    validaProdutoLista(item, pedido.getListaItemPedido());

    pedido.adicionaItens(item);

    listViewItensPedidos.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, pedido.getListaItemPedido().size() * 50));

    TabelaItensPedidoAdapter adapter = new TabelaItensPedidoAdapter(PedidoActivity.this, pedido.getListaItemPedido());
    listViewItensPedidos.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    Log.i(TAG, "Itens add "+pedido.getListaItemPedido().size());

    codProduto.setText("");
    codProduto.requestFocus(); //voltar o foco para o produto
}catch (MyException e){
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    
asked by anonymous 30.10.2014 / 12:07

1 answer

1

I think it's not working because you're setting the focus by the time you're still pushing the button (you're shifting focus from the on click).

One possible solution is to use a Handler. You add an attribute of type Handler in your class and onclick you send a message to the Handler.

See this example:

import android.os.Handler;
import android.os.Message;
...
final Handler myHandler = new Handler() {
    public void handleMessage(Message msg) {
        Log.i("HANDLER", "handleMessage::recebendo msg " + msg.what);
        codProduto.setText("");
        codProduto.requestFocus(); //voltar o foco para o produto
    }
};

Then in onClick you do, in the place where the focus request is, you send a message to the Handler:

myHandler.sendEmptyMessage(0);
    
30.10.2014 / 20:25