EditText SetPosition at the end

0

I'm trying to make when I click on my Edit cursor position go to the end of the text, my code is as follows:

Script

public class DetalhesCompraActivity extends Activity {

EditText tb_acrescimo;
EditText tb_desconto;
EditText tb_tot_pago;
EditText tb_obs;
EditText lb_total_mercadoria;
EditText lb_total_geral;
final int cont = MySingleton.getInstance().fornecedorNome.indexOf(MySingleton.getInstance().fornecedor_atual_edit);

// Name Bank
private static final String NOME_BANCO = "sisce_mob";

// Name Table
public static final String TABELA_NOME_OPE = "opeger";
public static final String TABELA_NOME_MER = "opeite";

protected SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_detalhes_compra);

    TextView lb_fornecedor_nome  = (TextView) findViewById(R.id.lb_fornecedor_nome);
    lb_total_mercadoria          = (EditText) findViewById(R.id.lb_total_mercadorias);
    lb_total_geral               = (EditText) findViewById(R.id.lb_total_geral);

    Button bt_nova_mercadoria  = (Button)   findViewById(R.id.bt_nova_mercadoria);
    Button bt_voltar           = (Button) findViewById(R.id.bt_log_voltar);
    Button bt_confirmar        = (Button) findViewById(R.id.bt_log_continuar);
    Button bt_excluir          = (Button) findViewById(R.id.bt_excluir);

    tb_obs       = (EditText)findViewById(R.id.tb_obs_compra);

    tb_acrescimo = (EditText)findViewById(R.id.tb_acrescimos);
    tb_desconto  = (EditText)findViewById(R.id.tb_descontos);
    tb_tot_pago  = (EditText)findViewById(R.id.tb_total_pago);

    tb_acrescimo.addTextChangedListener(tw_acrescimo);
    tb_desconto.addTextChangedListener(tw_desconto);
    tb_tot_pago.addTextChangedListener(tw_total_pago);

    db = DetalhesCompraActivity.this.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null);

    String data = MySingleton.getInstance().data_selecionada;

    String[] datSepareted = data.split("/");

    data = datSepareted[2] + datSepareted[1] + datSepareted[0];

    String tipo = MySingleton.getInstance().tipoAtual;;
    String cod  = MySingleton.getInstance().fornecedor_atual_edit_cod;

    Cursor c = db.query(TABELA_NOME_OPE, null, "caddat=? and cadtip=? and caddes=?", new String[]{data, tipo, cod}, null, null, null);

    c.moveToFirst();

    int codI = c.getColumnIndex("cadcod");
    int datI = c.getColumnIndex("caddat");
    int vacI = c.getColumnIndex("cadvac");
    int vdeI = c.getColumnIndex("cadvde");
    int valI = c.getColumnIndex("cadval");
    int obsI = c.getColumnIndex("cadobs");

    lb_fornecedor_nome.setText(MySingleton.getInstance().fornecedor_atual_edit);

    String codM   = "";
    String totalP = "";
    String acres  = "";
    String desc   = "";
    String obs    = "";
    String totalM = ""; 
    String totalG = "";

    if(!MySingleton.getInstance().alterando){
        if(c.getCount() > 0){
            codM   = c.getString(codI);
            totalP = c.getString(valI);//MySingleton.getInstance().fornecedorTotalP.get(cont);
            acres  = c.getString(vacI);
            desc   = c.getString(vdeI);
            obs    = c.getString(obsI);
        }


        c = db.query(TABELA_NOME_MER, null, "cadcod=?", new String[]{codM}, null, null, null);

        c.moveToFirst();

        Float totalMI   = 0.00f;
        int valP      = c.getColumnIndex("cadvto");

        for(int i = 0; i<c.getCount(); i++){
            Float tempI = Float.parseFloat(c.getString(valP));

            totalMI = totalMI + tempI;
            c.moveToNext();
        }

        totalM = String.format(Locale.US,"%.2f", totalMI);  

        MySingleton.getInstance().alterando = true;
    }else{
        totalM = MySingleton.getInstance().fornecedorTotalM.get(cont);
        totalP = MySingleton.getInstance().fornecedorTotalP.get(cont);
        acres  = MySingleton.getInstance().fornecedorAcres.get(cont);
        desc   = MySingleton.getInstance().fornecedorDesc.get(cont);
        obs    = MySingleton.getInstance().fornecedorObs.get(cont);
    }

    if(totalM.equals(""))
        totalM = "0.00";
    if(totalP.equals(""))
        totalP = "0.00";
    if(acres.equals(""))
        acres = "0.00";
    if(desc.equals(""))
        desc = "0.00";
    if(obs.equals(""))
        obs = "";

    Float intTotalM = Float.parseFloat(totalM);
    Float intAcres  = Float.parseFloat(acres);
    Float intDesc   = Float.parseFloat(desc);

    Float intTotalG = intTotalM + intAcres + intDesc;

    totalG = String.format(Locale.US,"%.2f", intTotalG);
    acres  = String.format(Locale.US,"%.2f", intAcres);
    desc   = String.format(Locale.US,"%.2f", intDesc);

    Float totalPF = Float.parseFloat(totalP);
    totalP = String.format(Locale.US,"%.2f", totalPF);

    lb_total_geral.setText(totalG);
    lb_total_mercadoria.setText(totalM);
    tb_tot_pago.setText(totalP);
    tb_acrescimo.setText(acres);
    tb_desconto.setText(desc);
    tb_obs.setText(obs);

    tb_acrescimo.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            int position = tb_acrescimo.length();
            Editable etext = tb_acrescimo.getText();
            Selection.setSelection(etext, position);
        }
    });


    tb_desconto.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            int i = tb_desconto.getText().length();
            tb_desconto.setSelection(i);

        }
    });

    tb_tot_pago.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            int i = tb_tot_pago.getText().length();
            tb_tot_pago.setSelection(i);
        }
    });

    bt_confirmar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            TextView lb_total_mercadoria = (TextView) findViewById(R.id.lb_total_mercadorias);
            TextView lb_total_geral      = (TextView) findViewById(R.id.lb_total_geral);
            tb_acrescimo                 = (EditText) findViewById(R.id.tb_acrescimos);
            tb_desconto                  = (EditText) findViewById(R.id.tb_descontos);
            tb_obs                       = (EditText) findViewById(R.id.tb_obs_compra);

            db = DetalhesCompraActivity.this.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null);

            String tipo = "2";
            String cod  = MySingleton.getInstance().fornecedor_atual_edit_cod;
            String teste = "";

            Cursor c = db.query(TABELA_NOME_OPE, null, "cadtip=? and caddes=?", new String[]{tipo, cod}, null, null, null);
            c.moveToFirst();

            ContentValues valores = new ContentValues();

            String dat = MySingleton.getInstance().data_selecionada;

            String[] datSepareted = dat.split("/");

            dat = datSepareted[2] + datSepareted[1] + datSepareted[0];

            String totalP = tb_tot_pago.getText().toString();
            String acres  = tb_acrescimo.getText().toString();
            String desc   = tb_desconto.getText().toString();

            Float totalPF = Float.parseFloat(totalP);
            Float acresF  = Float.parseFloat(acres);
            Float descF   = Float.parseFloat(desc);

            String vac = String.format(Locale.US,"%.2f", acresF);
            String vde = String.format(Locale.US,"%.2f", descF);
            String val = String.format(Locale.US,"%.2f", totalPF);
            String obs = tb_obs.getText().toString();;

            valores.put("caddat", dat);
            valores.put("cadtip", tipo);
            valores.put("caddes", cod);
            valores.put("cadvac", vac);
            valores.put("cadvde", vde);
            valores.put("cadval", val);
            valores.put("cadobs", obs);

            if(c.getCount() > 0){
                db.update(TABELA_NOME_OPE, valores, "cadtip=? and caddes=?", new String[]{tipo, cod});
            }else{
                db.insert(TABELA_NOME_OPE, null, valores);
            }

            c = db.query(TABELA_NOME_OPE, null, "cadtip=? and caddes=?", new String[]{tipo, cod}, null, null, null);

            c.moveToFirst();

            String codOper = c.getString(c.getColumnIndex("cadcod"));

            if(!codOper.equals("")){
                db.delete(TABELA_NOME_MER, "cadcod=?", new String[]{codOper});
            }

            int contMercadorias = MySingleton.getInstance().cadMercadoriaFornecedorCod.size();

            for(int i = 0; i < contMercadorias; i++){
                valores.clear();

                if(MySingleton.getInstance().cadMercadoriaFornecedorCod.get(i).equals(cod)){
                    String cadcpr = MySingleton.getInstance().cadMercadoriaCod.get(i);
                    String cadqua = MySingleton.getInstance().cadMercadoriaQuant.get(i);
                    String cadvun = MySingleton.getInstance().cadMercadoriaValUnit.get(i);
                    String cadvto = MySingleton.getInstance().cadMercadoriaValTotal.get(i);

                    valores.put("cadcod", codOper);
                    valores.put("cadcpr", cadcpr);
                    valores.put("cadqua", cadqua);
                    valores.put("cadvun", cadvun);
                    valores.put("cadvto", cadvto);

                    db.insert(TABELA_NOME_MER, null, valores);
                }
            }

            DetalhesCompraActivity.this.finish();
            Intent it = new Intent(DetalhesCompraActivity.this, ListFornecedoresActivity.class);
            startActivity(it); 
        }
    });

    bt_nova_mercadoria.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            tb_acrescimo                 = (EditText)findViewById(R.id.tb_acrescimos);
            tb_desconto                  = (EditText)findViewById(R.id.tb_descontos);
            tb_tot_pago                  = (EditText)findViewById(R.id.tb_total_pago);
            tb_obs                       = (EditText)findViewById(R.id.tb_obs_compra);


            String totalp = tb_tot_pago.getText().toString();
            String obs    = tb_obs.getText().toString();
            String acres  = tb_acrescimo.getText().toString();
            String desc   = tb_desconto.getText().toString();

            MySingleton.getInstance().fornecedorTotalP.set(cont, totalp);
            MySingleton.getInstance().fornecedorObs.set(cont, obs);
            MySingleton.getInstance().fornecedorAcres.set(cont, acres);
            MySingleton.getInstance().fornecedorDesc.set(cont, desc);

            DetalhesCompraActivity.this.finish();
            Intent it = new Intent(DetalhesCompraActivity.this, ListMercadoriasActivity.class);
            startActivity(it); 
        }
    });

    bt_voltar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            DetalhesCompraActivity.this.finish();
            Intent it = new Intent(DetalhesCompraActivity.this, ListFornecedoresActivity.class);
            startActivity(it); 
        }
    });

    bt_excluir.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String fAtual = MySingleton.getInstance().fornecedor_atual_edit;
            int cadI  = MySingleton.getInstance().fornecedorNome.indexOf(fAtual);
            int prodL = MySingleton.getInstance().cadMercadoriaFornecedorNome.size();

            MySingleton.getInstance().fornecedorTotalM.set(cadI, "");
            MySingleton.getInstance().fornecedorTotalG.set(cadI, "");
            MySingleton.getInstance().fornecedorTotalP.set(cadI, "");
            MySingleton.getInstance().fornecedorAcres.set(cadI, "");
            MySingleton.getInstance().fornecedorDesc.set(cadI, "");
            MySingleton.getInstance().fornecedorObs.set(cadI, "");

            for(int i = 0; i < MySingleton.getInstance().cadMercadoriaFornecedorNome.size();){
                String teste = MySingleton.getInstance().cadMercadoriaFornecedorNome.get(i);
                if(MySingleton.getInstance().cadMercadoriaFornecedorNome.get(i).equals(fAtual)){
                    MySingleton.getInstance().cadMercadoriaFornecedorCod.remove(i);
                    MySingleton.getInstance().cadMercadoriaFornecedorNome.remove(i);
                    MySingleton.getInstance().cadMercadoriaNome.remove(i);
                    MySingleton.getInstance().cadMercadoriaQuant.remove(i);
                    MySingleton.getInstance().cadMercadoriaUnid.remove(i);
                    MySingleton.getInstance().cadMercadoriaValTotal.remove(i);
                    MySingleton.getInstance().cadMercadoriaValUnit.remove(i);
                }else{
                    i = i +1;
                }
            }

            if(MySingleton.getInstance().fornecedorAlterado.get(cadI).equals("1")){
                MySingleton.getInstance().fornecedorAlterado.set(cadI, "0");
            }

            DetalhesCompraActivity.this.finish();
            Intent it = new Intent(DetalhesCompraActivity.this, ListFornecedoresActivity.class);
            startActivity(it); 
        }
    });
}

TextWatcher tw_acrescimo = new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {



        if (!s.toString().matches("^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$")) {
          String userInput = "" + s.toString().replaceAll("[^\d]", "");
          StringBuilder cashAmountBuilder = new StringBuilder(userInput);

          tb_desconto                  = (EditText) findViewById(R.id.tb_descontos);
          lb_total_geral               = (EditText) findViewById(R.id.lb_total_geral);

          while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
            cashAmountBuilder.deleteCharAt(0);
          }
          while (cashAmountBuilder.length() < 3) {
            cashAmountBuilder.insert(0, '0');
          }
          cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');

          tb_acrescimo.removeTextChangedListener(this);
          tb_acrescimo.setText(cashAmountBuilder.toString());

          tb_acrescimo.setTextKeepState(cashAmountBuilder.toString());
          Selection.setSelection(tb_acrescimo.getText(), cashAmountBuilder.toString().length());

          String strD  = tb_desconto.getText().toString();
          String strTM = tb_acrescimo.getText().toString();

          if(!strD.equals("") & !strTM.equals("")){
              Float d  = Float.parseFloat(tb_desconto.getText().toString());
              Float tm = Float.parseFloat(tb_acrescimo.getText().toString());
              Float a  = Float.parseFloat(lb_total_mercadoria.getText().toString());

              Float totalGeral = a + tm - d;

              String totalStr = String.format(Locale.US,"%.2f", totalGeral);

              lb_total_geral.setText(totalStr);
          }

          tb_acrescimo.addTextChangedListener(this);
        }
      }
};

TextWatcher tw_desconto = new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {

        if (!s.toString().matches("^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$")) {
            tb_desconto                  = (EditText) findViewById(R.id.tb_descontos);
            lb_total_geral               = (EditText) findViewById(R.id.lb_total_geral);

          String userInput = "" + s.toString().replaceAll("[^\d]", "");
          StringBuilder cashAmountBuilder = new StringBuilder(userInput);

          while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
            cashAmountBuilder.deleteCharAt(0);
          }
          while (cashAmountBuilder.length() < 3) {
            cashAmountBuilder.insert(0, '0');
          }
          cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');

          tb_desconto.removeTextChangedListener(this);
          tb_desconto.setText(cashAmountBuilder.toString());

          tb_desconto.setTextKeepState(cashAmountBuilder.toString());
          Selection.setSelection(tb_desconto.getText(), cashAmountBuilder.toString().length());

          String strD  = tb_desconto.getText().toString();
          String strTM = tb_acrescimo.getText().toString();

          if(!strD.equals("") & !strTM.equals("")){
              Float d  = Float.parseFloat(tb_desconto.getText().toString());
              Float tm = Float.parseFloat(tb_acrescimo.getText().toString());
              Float a  = Float.parseFloat(lb_total_mercadoria.getText().toString());

              Float totalGeral = a + tm - d;

              String totalStr = String.format(Locale.US,"%.2f", totalGeral);

              lb_total_geral.setText(totalStr);
          }
          tb_desconto.addTextChangedListener(this);

        }
      }
};

TextWatcher tw_total_pago = new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {

        if (!s.toString().matches("^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$")) {
          String userInput = "" + s.toString().replaceAll("[^\d]", "");
          StringBuilder cashAmountBuilder = new StringBuilder(userInput);

          while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
            cashAmountBuilder.deleteCharAt(0);
          }
          while (cashAmountBuilder.length() < 3) {
            cashAmountBuilder.insert(0, '0');
          }
          cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');

          tb_tot_pago.removeTextChangedListener(this);
          tb_tot_pago.setText(cashAmountBuilder.toString());

          tb_tot_pago.setTextKeepState(cashAmountBuilder.toString());
          Selection.setSelection(tb_tot_pago.getText(), cashAmountBuilder.toString().length());

          tb_tot_pago.addTextChangedListener(this);
        }
      }
};

}

But it works in Android 2.3 API but does not work in 4.1, does anyone know what I should do?

    
asked by anonymous 30.07.2014 / 21:20

1 answer

1

Try this out

tb_acrescimo.setSelection(tb_acrescimo.getText().length()); 

or

tb_acrescimo.setText("Updated Text From another Activity");
int position = tb_acrescimo.length();
Editable etext = tb_acrescimo.getText();
Selection.setSelection(etext, position);

Or put this in xml

android:ellipsize="end"
    
30.07.2014 / 21:30