SkyeBoniwell
SkyeBoniwell

Reputation: 7092

Pass in different types of views to a method

I want to create a method that can either clear the text of an EditText or a TextView.

How can I make it so that either type of view can be passed in and cleared?

Is this possible in Android?

package com.androidapps.x90.battleexchange;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import java.text.DecimalFormat;

public class MainActivity extends AppCompatActivity {

    //declare variables
    double arrowBattleRate = 55.1;
    double swordBattleRate = 100.9;
    double amountEntered;
    double convertedValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText currencyValue = (EditText) findViewById(R.id.txtCurrency);
        final RadioButton swordsToArrows = (RadioButton) findViewById(R.id.radSwordsToArrows);
        final RadioButton arrowsToSwords = (RadioButton) findViewById(R.id.radArrowToSwords);
        final TextView battleResult = (TextView) findViewById(R.id.txtResult);
        Button convert = (Button) findViewById(R.id.btnConvert);

        convert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                amountEntered = Double.parseDouble(magicValue.getText().toString());

                DecimalFormat tenth = new DecimalFormat("#.#");

                if(arrowsToSwords.isChecked()) {
                    clearValuesFromControls(battleResult);
                    convertedValue = amountEntered * arrowBattleRate;
                    battleResult.setText(tenth.format(convertedValue) + " Swords.");
                }
                if(swordsToArrows.isChecked()){
                    convertedValue = amountEntered * swordsBattleRate;
                    battleResult.setText(tenth.format(convertedValue) + " Arrows.");
                }

            }
        });
    }
    //pass in either EditText or TextView control
    public void clearValuesFromControls(control) {
        control.setText("");
    }
}

Upvotes: 1

Views: 43

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93561

EditText derives from TextView, so just pass in a TextView.

Upvotes: 4

Related Questions