我試圖建立一個onClickListner在while循環是這樣的:在while循環中設置OnClickListener?
View inflaterLayout;
LinearLayout myLayout = (LinearLayout)findViewById(R.id.linearLayout2);
while (counter < 5) {
inflaterLayout = LayoutInflater.from(getBaseContext()).inflate(R.layout.newplayerlayout, null);
myLayout.addView(inflaterLayout);
Button testButton = (Button) myLayout.findViewById(R.id.button2);
testButton.setId(testButtonArray[counter]);
((TextView) myLayout.findViewById(R.id.textView1)).setId(testTextArray[counter]);
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
((TextView) findViewById(testTextArray[counter])).setText("Hi!");
}
});
counter++;
}
當你點擊它會改變未來的TextView的它的testButton的任何一個我以爲它會做的是!但只有第一個按鈕,這充氣工程!有誰知道我做錯了什麼?
基本上我想要完成的是,我正在充氣具有加號按鈕,減號按鈕和文本視圖的佈局,所以我希望能夠設置一個onClickListener,它將添加和減去而不必設置一百萬個單獨的onClickListeners!
我想你應該保存在數組中的按鈕refrence。然後在循環外部設置onClicklistener。 –
我試過了,我只是把它放在一個循環中,所以每個人都知道我正在努力完成什麼。 –
我從你的新描述中更新了我的答案。 – Sam