我一直试图弄清楚这一点,因为我想根据计算结果添加图像。我正在创建一个BMI计算器。我在Android工作室完美运行。如果结果是瘦或胖的图像,如果它说超重,只是想添加一个瘦的图像。这是代码。谢谢。
package ie.wit.fitnessmadeeasy;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class BmiActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi);
final Button calc = (Button) findViewById(R.id.calc);
final EditText weight = (EditText) findViewById(R.id.weight);
final EditText height = (EditText) findViewById(R.id.height);
final TextView result = (TextView) findViewById(R.id.result);
calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String heightStr = height.getText().toString();
String weightStr = weight.getText().toString();
if (heightStr != null && !"".equals(heightStr)
&& weightStr != null && !"".equals(weightStr)) {
float heightValue = Float.parseFloat(heightStr) / 100;
float weightValue = Float.parseFloat(weightStr);
float bmi = weightValue / (heightValue * heightValue);
String bmiLabel = "";
if (bmi <= 15) {
bmiLabel = getString(R.string.very_very_skinny);
} else if (bmi > 15 && bmi <= 16) {
bmiLabel = getString(R.string.very_skinny);
} else if (bmi > 15 && bmi <= 18.5) {
bmiLabel = getString(R.string.skinny);
} else if (bmi > 18.5 && bmi <= 25) {
bmiLabel = getString(R.string.normal);
} else if (bmi > 25 && bmi <= 30) {
bmiLabel = getString(R.string.overweight);
} else if (bmi > 30 && bmi <= 35) {
bmiLabel = getString(R.string.obese_series_i);
} else if (bmi > 35 && bmi <= 40) {
bmiLabel = getString(R.string.obese_series_ii);
} else {
bmiLabel = getString(R.string.obese_series_iii);
}
bmiLabel = bmi + "\n\n" + bmiLabel;
result.setText(bmiLabel);
}
}
});
}
}
答案 0 :(得分:0)
嗯,这只是出于好的事情。 Android手册。
您将需要:
你的drawable文件夹中有2个drawables,一个瘦,一个胖
final ImageView imageViewBMI = (ImageView) findViewById(R.id.image_bmi);
然后在你的if / else
里面的某个地方imageViewBMI.setImageResource(R.drawable.skinny);