Geebs Geebs - 6 months ago 14
Android Question

clearing different edittexts with different buttons while reusing same code

I have two different edittext fields, each with a 'clear' button to clear the inputted text. I can clear both fields like so:

XML:

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fieldOneInput"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/clearButtonText"
android:id="@+id/clearTextField1"
android:onClick="clearTextField1"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fieldTwoInput"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/clearButtonText"
android:id="@+id/clearTextField2"
android:onClick="clearTextField2"/>


Java:

public void clearTextField1(View view){
EditText fieldOneInput = (EditText) findViewById(R.id.fieldOneInput);
fieldOneInput.setText("");
}

public void clearTextField2(View view){
EditText fieldTwoInput = (EditText) findViewById(R.id.fieldTwoInput);
fieldOneInput.setText("");
}


This isn't practical if I have multiple edittexts each with a 'clear' button. How would I go about clearing different edittexts fields using different buttons while reusing the same (java) code?

Answer

You can achieve this using following code:

public class AbcActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //... your code here, to get button objects from xml file
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                clearEditText(R.id.editText1);
                break;
            case R.id.button2:
                clearEditText(R.id.editText2);
                break;
            case R.id.button3:
                clearEditText(R.id.editText3);
                break;
            case R.id.button4:
                clearEditText(R.id.editText4);
                break;
        }
    }

    private void clearEditText(int editTextId) {
        findViewById(editTextId).setText("");
    }

}