Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiple (dynamic) EditText and onFocusChange problems
    primarykey
    data
    text
    <p>I generate multiple <code>EditText</code> in a for-loop and want to update a "score" when focus is lost from one of the <code>EditText</code>s. I also wish to check that the input is valid and if not, empty the EditText and set focus back to it.</p> <p>The following code adds <code>EditTexts</code> and a <code>onFocusChangeListener</code>.</p> <p>The problem is that when a score is not valid (<code>updateScore(id)</code> returns false), I want to empty the <code>EditText</code> and set the focus back to this view.</p> <p>The problem in my code is that if I enter a value in <code>EditText</code> <strong>A</strong> that are not valid, and then click in <code>EditText</code> <strong>B</strong>. Both <strong>A</strong> <em>and</em> <strong>B</strong> have focus... I only want A to have focus...</p> <p>How can I set the focus back to the previous EditText and be ready for new inputs to this view?</p> <pre><code> for (int player = 0; player &lt; numPlayers; player++) { EditText valueET = new EditText(this); valueET.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.v("Focus", "Lagrer unna den som har blitt klikket, " + String.valueOf(v.getId())); etHasFocus = (EditText) v; } }); valueET.setOnFocusChangeListener(new OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if(!hasFocus) { if(!updateScore(v.getId())) { if (etHasFocus != null &amp;&amp; v.getId() != etHasFocus.getId()) etHasFocus.clearFocus(); v.requestFocus(); } }); valueET.setId(200+player*100+row); valueET.setInputType(InputType.TYPE_CLASS_NUMBER); valueET.setTextColor(Color.BLACK); valueET.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); tr.addView(valueET); } tl.addView(tr, new TableLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); </code></pre> <p>The code for updateScore(id) is (simplified):</p> <pre><code>boolean updateScore(int id) { EditText t = (EditText) findViewById(id); String text = t.getText().toString(); if( !text.equals("")) { int score = Integer.parseInt(text); } if(score != 9) return false; TextView total = (TextView) findViewById(ID_toal); t2.setText(String.valueOf(score)); return true; } </code></pre> <hr> <p>Code is updated, problem now is that onClick never is called... (So etHasFocus = null)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload