我有MainText1显示文本,当您单击Menu MainText1中的按钮3时,显示来自超类Text的text3。我想要的是动态当你点击任何按钮时它会读取数字并显示相应的文字,这就是全部。 ;) 我想在我的活动中摆脱switch case,所以我现在正在尝试2天:(动态更改字符串变量的名称,但我认为我使用了错误的代码,因为字符串变量与资源不同(困惑),这是我的代码,本周末这对我很有挑战性:
public class MainText1 extends Text {
String
tx1=text1,tx2=text2,tx3=text3,
tx,stringReceived;//text1,text2...textn strings coming from the Super class Text
num = Integer.parseInt(getIntent().getStringExtra("somekey1")); // this data is coming from the menu, it depends on which button is clicked
tx="text"+num; // text is the name of the string variable, it should be in format like that : text1,text2,...textn which have predefined string content
stringId = getApplicationContext().getResources().getIdentifier(tx, "string", getPackageName());
if (stringId > 0) {
stringReceived=getApplicationContext().getResources().getString(stringId);
答案 0 :(得分:0)
我猜你正在尝试做的是更改TextView内容。所以,您可以执行以下操作:
public YourActivity extends Activity {
//Here you will declare your layout items
private Button button1;
private Button button2;
private Button button3;
private TextView txtView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//Here you will get you layout elements
button1 = (Button) findViewById(R.id.button1_id);
button2 = (Button) findViewById(R.id.button2_id);
button3 = (Button) findViewById(R.id.button3_id);
txtView = (TextView) findViewById(R.id.txtview_id);
//Now you will have to set the onClickListeners
button1.addOnCLickListener(new OnClickListener() {
@Override
private onClick() {
//Set the text in the text view to the string related
//to button1
txtView.setText(getResources()
.getString(R.string.button1_string);)
}
});
button2.addOnCLickListener(new OnClickListener() {
@Override
private onClick() {
//Set the text in the text view to the string related
//to button2
txtView.setText(getResources()
.getString(R.string.button2_string);)
}
});
button3.addOnCLickListener(new OnClickListener() {
@Override
private onClick() {
//Set the text in the text view to the string related
//to button3
txtView.setText(getResources()
.getString(R.string.button3_string);)
}
});
}
}
这应该可以解决问题。虽然像其他人建议的那样,你应该在编码之前看一些教程