我制作了一个应用程序,用于计算另一个 Activity 中出现的一串值。我的应用程序有 3 个 editTexts
和 1 个按钮
。如果我们按下按钮计算
并输入编辑文本,计算值将显示在第二个 Activity 中。我成功了,但我的问题是,如果用户将任何框留空并按下按钮,系统将强制关闭。为了避免这种情况,我在图形布局中制作了 editText
并预先输入了提示。但是,如果用户在再次编辑 editText
后意外按下按钮,系统会显示强制关闭。
我尝试了很多 if else
方法,但它不起作用。有人向我展示了一种检查所有 editText
框的正确方法。
public class Screen1 extends Activity {
public static StringBuilder EXTRA_MESSAGE=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
Button bu1= (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View message)
{ int f1,f3,f4;
String vis;
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
String e1=t1.getText().toString();
String e3= t3.getText().toString();
String e4= t4.getText().toString();
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1)
{
sb.append(String.format("%.1f", i)+" mcg = "+(f1*60*i*f4)/(f3*1000)+"\n");
}
vis=sb.toString();
Intent intent = new Intent(message.getContext(),Screen2.class);
intent.putExtra("EXTRA_MESSAGE",vis);
startActivity(intent);
}
});
}
}
最佳答案
使用[TextUtils][1]
检查onClick
内的isEmpty()
文本:
@Override
public void onCreate(Bundle savedInstanceState){
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
Button bu1 = (Button) findViewById(R.id.bu);
bu1.setOnClickListener(this);
}
@Override
public void onClick(View message){
boolean foundEmpty = false;
if(TextUtils.isEmpty(t1.getText())) {
foundEmpty = true;
t1.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t2.getText()){
foundEmpty = true;
t2.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t3.getText()){
foundEmpty = true;
t3.setError("Please enter a value");
}
if(!foundEmpty){
/* none of your text fields are empty */
int f1, f3, f4;
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
final StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1) {
sb.append(String.format("%.1f", i)+
" mcg = "+
(f1*60*i*f4)/(f3*1000)+"\n");
}
final String vis = sb.toString();
Intent intent = new Intent(message.getContext(), Screen2.class);
intent.putExtra("EXTRA_MESSAGE", vis);
startActivity(intent);
}
}
关于java - 除非整个盒子都填满,否则不要进入下一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305215/