2016-11-09 3 views
0

У меня в настоящее время есть 2 на одном из моих экранов, в котором мне нужны слушатели, чтобы обновлять данные, когда один из них меняется, но я не уверен, как настроить его, не имея 24 отдельных частей кода для слушателей. Ответ, вероятно, очень очевиден, но я не могу это понять, я нашел несколько подобных вопросов, но не мог заставить его работать сам.Несколько addTextChangedListeners без дублирующего кода

Вот мой код, как он стоит:

private void loadPage() { 
    round1Boxer1Input = (EditText) findViewById(R.id.round1Boxer1Input); 
    totalBoxer1Text = (TextView) findViewById(R.id.totalBoxer1Text); 
    round2Boxer1Input = (EditText) findViewById(R.id.round2Boxer1Input); 
    round3Boxer1Input = (EditText) findViewById(R.id.round3Boxer1Input); 
    round4Boxer1Input = (EditText) findViewById(R.id.round4Boxer1Input); 
    round5Boxer1Input = (EditText) findViewById(R.id.round5Boxer1Input); 
    round6Boxer1Input = (EditText) findViewById(R.id.round6Boxer1Input); 
    round7Boxer1Input = (EditText) findViewById(R.id.round7Boxer1Input); 
    round8Boxer1Input = (EditText) findViewById(R.id.round8Boxer1Input); 
    round9Boxer1Input = (EditText) findViewById(R.id.round9Boxer1Input); 
    round10Boxer1Input = (EditText) findViewById(R.id.round10Boxer1Input); 
    round11Boxer1Input = (EditText) findViewById(R.id.round11Boxer1Input); 
    round12Boxer1Input = (EditText) findViewById(R.id.round12Boxer1Input;) 

    final EditText[] boxer1List = {round1Boxer1Input, round2Boxer1Input, round3Boxer1Input, round4Boxer1Input, 
      round5Boxer1Input, round6Boxer1Input, round7Boxer1Input, round8Boxer1Input, round9Boxer1Input, 
      round10Boxer1Input, round11Boxer1Input, round12Boxer1Input}; 

    round1Boxer1Input.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

     } 

     @Override 
     public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

     } 

     @Override 
     public void afterTextChanged(Editable editable) { 
      totalBoxer1Text.setText(String.valueOf(addRoundsBoxer1(boxer1List))); 
     } 
    }); 
} 

Как она стоит, я думаю, что я должен сделать 24 из тех слушателей, которые я предполагаю, что это не лучший способ сделать это.

+0

Создайте внутренний класс, который реализует TextWatcher и принимает вид (ваш EditText) или идентификатор Ressource в структурной структуре. В методе afterTextChanged вы можете получить доступ к идентификатору View или Ressource и решить, что делать. Соответствующе: http://stackoverflow.com/questions/22866060/how-to-get-the-view-in-textwatcher-method-context –

ответ

0

Для этого конкретного случая, почему не существует метода, который принимает EditText и применяет к нему TextWatcher? например

protected void applyTextWatcher(EditText roundInput, TextView boxerTotalText, EditText[] roundInputList){ 
    roundInput.addTextChangedListener(new TextWatcher() { 
     .... 
     @Override 
     public void afterTextChanged(Editable editable) { 
      boxerTotalText.setText(String.valueOf(sumRounds(roundInputList))); 
     } 
    }); 
} 

Что вы могли бы использовать с помощью:

for(EditText roundInput : boxer1List) 
    applyTextWatcher(roundInput, totalBoxer1Text, boxer1List); 

Хотя, вы по-прежнему будете дублировать много кода здесь, и это не очень гибкие (т.е. более/менее раунды будут среднее развертывание изменений кода), где вы можете захотеть использовать более объектно-ориентированный подход. например

Вместо списка EditTexts без реальной ссылки, вы могли бы иметь

public class Round { 
    int roundNumber; 

    int boxer1Score; 
    int boxer2Score; 
} 

public class RoundViewHolder { 
    Round round; 

    EditText boxer1Input; 
    EditText boxer2Input; 
} 

Тогда, вы бы иметь List<RoundViewHolder> работать с, а не только в EditTexts, который связывает непосредственно с Round, который поможет вам с динамически созданным EditTexts на основе того, сколько раундов действительно произошло.

Это немного псевдокод и не все, что вам нужно, но это должно указывать на вас в правильном направлении.

+1

Спасибо! :) Гораздо лучше, чем я должен был сделать это раньше! – ChappyHova

Смежные вопросы