如何将TextView值转换为Integer
问题描述:
编程战士的美好日子,请帮助我解决我的这个简单问题,我是android的新手.如何将TextView值转换为Integer.请查看我随附的代码,谢谢.
Good day programming warriors, please help me to this simple problem of mine, i'm new to android. How can I How to convert TextView value to Integer. please see my attached codes, thank you.
public class appleTrivia extends AppCompatActivity {
public int total = 0;
public int score = 40;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apple_trivia);
TextView scoreLabel = (TextView) findViewById(R.id.labelScore);
scoreLabel.setText("Score: " + score);
scoreLabel.setText("Score: " + getIntent().getExtras().getInt("points", 0));
try {
total = Integer.parseInt("score: " + scoreLabel);
}
catch (NumberFormatException nfe )
{
}
}
public void onClickProceed (View view) {
Intent intent = new Intent(this, cherry.class);
startActivity(intent);
Toast.makeText(appleTrivia.this, "Your score is:" + total, Toast.LENGTH_LONG).show();
}
}
我需要将scoreLabel值转换为整数,以便可以将其添加到另一个分数中,谢谢.PS.Toast.makeText(appleTrivia.this,您的分数是:" +总计,Toast.LENGTH_LONG).show();给我0分.
I need to convert scoreLabel value to integer so I can add it to another score, thank you. PS. Toast.makeText(appleTrivia.this, "Your score is:" + total, Toast.LENGTH_LONG).show(); give's me 0 score.
答
首先,您需要使用regex删除 Score:
文本:
First, you need to remove the Score :
text using regex maybe :
String str = scoreLabel.getText().toString();
str = str.replaceAll("[^-?0-9]+", "");
然后将其解析为整数:
int total = Integer.parseInt(str);
编辑
public class appleTrivia extends AppCompatActivity {
public int total = 0;
public int score = 40;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apple_trivia);
TextView scoreLabel = (TextView) findViewById(R.id.labelScore);
scoreLabel.setText("Score: " + score);
scoreLabel.setText("Score: " + getIntent().getExtras().getInt("points", 0));
try {
String str = scoreLabel.getText().toString();
str = str.replaceAll("[^-?0-9]+", "");
total = Integer.parseInt(str);
}
catch (NumberFormatException nfe )
{
}
}
public void onClickProceed (View view) {
Intent intent = new Intent(this, cherry.class);
startActivity(intent);
Toast.makeText(appleTrivia.this, "Your score is:" + total, Toast.LENGTH_LONG).show();
}
}