我有Android的GridView的怪異問題。我創建一個3x4網格並將按鈕插入該網格。當用戶點擊該按鈕時,我想要改變按鈕的背景。對於除第一個按鈕(索引爲0 - 左上角的那個按鈕)之外的所有按鈕,這都工作得很好。無論我做什麼,OnClick事件偵聽器都根本不會觸發該按鈕。的Android GridView的第一個按鈕不工作
這裏就是我創建視圖代碼:
public View getView(int position, View convertView, ViewGroup parent) {
Button imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.w("NOVO", "narejena nova celica");
imageView = new Button(mContext);
imageView.setPadding(8, 8, 8, 8);
} else {
Log.w("STARO", "stara celica");
imageView = (Button) convertView;
}
imageView.setEnabled(true);
int visina = parent.getHeight();
int sirina = parent.getWidth();
float dip = mContext.getResources().getDisplayMetrics().density;
float margin = 10*dip;
int view_height = (int)(visina - 3*margin)/4;
int view_width = (int)(sirina - 2*margin)/3;
int view_dim = 0;
if (view_height <= view_width)
view_dim = view_height;
else
view_dim = view_width;
imageView.setLayoutParams(new GridView.LayoutParams(view_dim, view_dim));
imageView.setId(position);
imageView.setOnClickListener(celice.get(position));
/*imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Toast toast = Toast.makeText(mContext, v.getId() + "bla", Toast.LENGTH_SHORT);
//toast.show();
celice.get(v.getId()).celicaVisible(4000);
}});*/
celice.get(position).id = position;
celice.get(position).setButton(imageView);
return imageView;
}
如果我更換
imageView = (Button) convertView;
與
imageView = new Button(mContext);
那麼的onClick()被炒魷魚,但後臺仍不會改變。所有其他按鈕按預期工作。
這裏是負責實際工作的自定義類「賽利卡」 - 改變背景...
public class Celica implements OnClickListener {
public boolean odkrit;
public boolean najden;
public int id;
public Drawable slikca1, slikca2;
public Celica par;
private Timer tim;
public Button but;
public Context con;
static int buttonsVisible = 0;
Celica(Drawable s1, Drawable s2) {
this.slikca1 = s1;
this.slikca2 = s2;
}
void celicaVisible(int millis) {
if (odkrit)
return;
Log.w("TEST", "prizganih " + buttonsVisible);
if (buttonsVisible >= 2)
return;
odkrit = true;
buttonsVisible++;
tim = new Timer();
tim.schedule(new timerDone(), millis);
((Activity)con).runOnUiThread(new Runnable() {
@Override
public void run() {
but.setBackground(slikca2);
}
});
}
void setButton(Button b) {
but = b;
((Activity)con).runOnUiThread(new Runnable() {
@Override
public void run() {
but.setBackground(slikca1);
}
});
}
class timerDone extends TimerTask {
@Override
public void run() {
if (!najden) {
odkrit = false;
((Activity)con).runOnUiThread(new Runnable() {
@Override
public void run() {
but.setBackground(slikca1);
}
});
}
buttonsVisible--;
tim.cancel();
}
}
@Override
public void onClick(View v) {
celicaVisible(4000);
}
}
只是使用'TextView'而不是'Button' –
爲什麼這應該有什麼不同?儘管我嘗試過 - 沒有改變。 – user3082900
@ user3082900檢查我的答案... –