我試圖創建Android的一個GridView下面的例子here,只是按鈕除了圖像。這是我改變了代碼:爲什麼onClickListener在這個例子中不再工作?
public class ButtonAdapter extends BaseAdapter {
private Context mContext;
private String[] filesnames = {
"File 1",
"File 2",
"Roflcopters",
"File 1",
"File 2",
"Roflcopters",
"File 1",
"File 2",
"Roflcopters",
"File 1",
"File 2",
"Roflcopters"
};
public ButtonAdapter(Context c) {
mContext = c;
}
public int getCount() {
return filesnames.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
Button btn;
if (convertView == null) {
// if it's not recycled, initialize some attributes
btn = new Button(mContext);
btn.setLayoutParams(new GridView.LayoutParams(100, 85));
btn.setPadding(8, 8, 8, 8);
}
else {
btn = (Button) convertView;
}
btn.setText(filesnames[position]);
// filenames is an array of strings
btn.setTextColor(Color.WHITE);
btn.setBackgroundResource(R.drawable.sample_0);
btn.setId(position);
return btn;
}
}
,當然,我略微改變了主要的Java代碼,我已經叫這個適配器和活性不同:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_route);
GridView gridview = (GridView) findViewById(R.id.selectroute_view);
gridview.setAdapter(new ButtonAdapter(this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(SelectRoute.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
一切正常,到目前爲止, ,除了點擊其中一個按鈕時,我不會收到吐司消息。我沒有看到任何錯誤 - 那麼我做錯了什麼?
我會嘗試,但我不明白爲什麼它不會像原來的例子工作... – Alex
隨着你的建議我有局部變量訪問等問題 – Alex