[英]Android Pass value to another activity
我有一个带有30个按钮的MainActivity
(标识: imageButton1
, imageButton2
...)。 在click事件上,我正在启动一个名为KlikNaDugme
的新活动:
主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
buttons = new ImageButton[30];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
}
我正在尝试将vr
传递给KlikNaDugme
活动,该活动被声明为public int
。
KlikNaDugme活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klik_na_dugme);
int x = getIntent().getExtras().getInt("vrijednost");
System.out.println(x);
}
问题在于,它始终获得29的值。如何正确传递ID?
将i
的值存储在按钮的标签中:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(getResources().getIdentifier("imageButton" + (i + 1), "id", this.getPackageName()));
buttons[i].setTag(i);
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class)
myIntent.putExtra("vrijednost", Integer.parseInt(view.getTag().toString()));
startActivity(myIntent);
}
});
}
}
问题出在这里:
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
您正在做的是创建一个无效的资源引用 ,然后在该引用上找到您的视图,这显然是错误的。 请记住, findViewById()
需要一个由Android Studio本身生成的资源ID。
解决方案是将所有20-30个视图引用保存在一个数组中,然后使用循环在其上设置单击侦听器
将vr值添加为按钮的标签,然后使用getTag()方法在onclicklistener中获取vr值
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setTag(vr); // This will se the vr value as tag
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int vr = (int)view.getTag() // this will get the vr value from view
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
R.id.what_ever将为您提供由Android Studio在R类中生成的整数值,而不是what_ever字符串。 您应该使用getResources().getIdentifier()
来获取正确的资源ID,并将其传递给findViewById()
。
请尝试此代码。 它将为您提供正确的ImageButtons ID:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "imageButton" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = (ImageButton) findViewById(resID);
buttons[i].setTag(i);
//vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View args0) {
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", (int)args0.getTag());
startActivity(myIntent);
}
});
}
好好享受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.