说实话,这个功能很简单,也不知为何刚开始做这个简单小功能时老是程序崩溃,记录下来仅供日后参考了。
布局界面如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:layout_margin="5dp"
/>
<Button
android:id="@+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交"
android:layout_margin="5dp"
/>
</LinearLayout>
布局界面只要设置好需要输入的类型(文本、数字、密码等)就可以了。
Activity关键代码如下:submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String num = number.getText().toString();
if (TextUtils.isEmpty(num)) {
Toast.makeText(MainActivity.this, "数字不能为空", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "提交成功!数字为:" + Double.parseDouble(num), Toast.LENGTH_SHORT).show();
}
}
});
获取EditText控件的内容只需要记住把字符串类型转换成项目中所需的数字类型(是包装类,而不是简单地基本类型)就可以了。