好的,所以我有一个buttonarray,我都使用for循环进行实例化。每个按钮都有一个ID以及一个onclicklistener。 onclicklistener打开一个新的意图(所有按钮都相同的新活动),并且根据所按下按钮的ID,新活动应显示某个pdf文件。
问题是我数组中的最后一个数字被解析为新的意图。因此,所有按钮都具有相同的ID,而不是从0增加到45。
Sheetmusiclist.java(mainactivity):
Button sheetsButtons[];
int id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheetsmusiclist);
sheetsButtons = new Button[46];
for(int i=0;i<46;i++){
id = i;
sheetsButtons[i] = new Button(this);
sheetsButtons[i].setId(i);
View.OnClickListener mThisButtonListener = new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(SheetMusicList.this, SheetMusic.class);
intent.putExtra("id", id);
startActivity(intent);}};
sheetsButtons[i].setOnClickListener(mThisButtonListener);
}}
然后,在下一个活动(Sheetmusic.java)中,我回想意图并获取ID。然后根据ID显示pdf文件。但是在所有情况下,都会显示数组中的最后一个ID:45。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheetmusic);
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null){
id = (int) bd.get("id"); //ID here is always 45
}
//a switch here with id -> pdf file name
有人知道吗?
最佳答案
使用intent.putExtra("id", v.getId());
代替intent.putExtra("id", id);
。
目前,您正在将您的id变量另存为该类的全局变量,并为其分配了i。在完成所有Button
的创建后,当您单击Button
时,您的id变量将保留为for
循环中的最后一个i,这就是为什么您总是在意图中获得“最后一个”元素的原因。
通过使用v.getId();
来获得单击按钮的ID,该ID在创建过程中分配为i,因此Buttons
的所有ID均不同。
希望这可以帮助。祝好运 :)