如何从两个编辑文本中获取所选数字值的总和

How to get a Sum of selected Number value from two edit texts

我有两个 editText,就像第一个编辑文本一样,我们正在输入一些数字,例如 12324582...在该值中,我们正在从第一个 editText 中搜索一个数字...这是第二个 editText...我有一个按钮和一个 textView...

每当我点击按钮时,结果将得到文本视图上显示的搜索数字的总和。

例如:

EditText1= 12345252(有3个2)

我要搜索2个号码

EditText2= 2

每当我单击按钮时,textView 都会显示数字 6 (2+2+2)。

我建议使用 apache.common.lang 中的 StringUtils class。 您需要做的就是计算 EditText1 中 EditText2 的出现次数。 所以使用这个方法:

int count = StringUtils.countMatches(TextEdit1.getText(), TextEdit2.getText());

之后在 textView 中设置文本,它是出现次数乘以 EditText2 中的数字

textView.setText(Integer.toString(count * Integer.parseInt(TextEdit2.getText()))

试试下面的代码

public class MainActivity extends AppCompatActivity {


EditText edtInput, edtSearch, edtOutPut;
Button btnCalculate;
int lastIndex = 0;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edtInput = (EditText) findViewById(R.id.edtInput);
    edtSearch = (EditText)findViewById(R.id.edtSearch);
    edtOutPut = (EditText)findViewById(R.id.edtOutPut);

    btnCalculate = (Button)findViewById(R.id.btnCalculate);

    btnCalculate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            count=0;
            lastIndex = 0;
            calculate();
        }
    });
}

private void calculate() {
    while(lastIndex != -1){

        lastIndex = edtInput.getText().toString().indexOf(edtSearch.getText().toString(),lastIndex);

        if(lastIndex != -1){
            count ++;
            lastIndex += edtSearch.getText().toString().length();
        }
    }
    edtOutPut.setText(""+(count*Integer.parseInt(edtSearch.getText().toString())));
}
}