我对编程很新,我试图教自己如何为Android设备编写应用程序。我目前正在使用官方Android开发者网站的原始用户指南。我试图从用户获取整数输入,一旦点击一个按钮,该数字将乘以.1 *(从第二个用户edittext框中取得的数字)。例如,在第一个文本框中,用户将输入100,在第二个文本框中,用户将输入10.第三个文本框中的结果将是10/100 * 100,这将是10.我将如何进行此操作和确保结果显示在第三个文本框中。
这是我到目前为止的代码
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class FirstActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.discountpricecalculator.MESSAGE";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
//Do something in response to button
}
}
答案 0 :(得分:3)
使用
获取edittext值EditText e1 = (EditText) findViewById(R.id.edittext1);
String myEditValue = e1.getText().toString();
int value = Integer.parseInt(myEditValue); //similarly for second text view
现在进行所需的数学运算
value 3=value2*value1
与设定值类似
EditText e3 = (EditText) findViewById(R.id.edittext3);
e3.setText(Value3.toString());
答案 1 :(得分:1)
这是一个相对完整的例子。你必须自己找出XML视图。
public class YourActivity extends Activity {
private EditText first;
private EditText second;
private TextView result;
private Button button;
public void onCreate(Bundle instanceState) {
super.onCreate(instanceState);
first = (EditText)findViewById(R.id.idoffirst);
second = (EditText)findViewById(R.id.idofsecond);
result = (TextView)findViewById(R.id.idofresult);
button = (Button)findViewById(R.id.idofbutton);
// limit input to numbers only (or use android:inputType="number" in XML)
first.setInputType(InputType.TYPE_CLASS_NUMBER);
second.setInputType(InputType.TYPE_CLASS_NUMBER);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// NOTE: You should deal with number format exceptions here (use try-catch)
float firstValue = Float.parseFloat(first.getText());
float secondValue = Float.parseFloat(second.getText());
result.setText(Float.toString(firstValue * secondValue));
}
});
}
}