我正在为gridview使用自定义适配器类,并且在此中有一个Button和一个TextView。我在gridview中显示calander月,当我点击Button时我想在Toast中显示按钮的文本(即当前日期)。但它显示28总是即最后一个按钮的gridview值。 我的getView()方法代码是:
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.screen_gridcell, parent, false);
}
if (sp != null) {
}
// Get a reference to the Day gridcell
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
gridcell.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) { // HERE I AM SHOWING TEXT OF BUTTON
// TODO Auto-generated method stub
Toast.makeText(getActivity(), ""+gridcell.getText().toString(), Toast.LENGTH_LONG).show();
}
});
gridcell.setOnLongClickListener(this);
// ACCOUNT FOR SPACING
Log.v(tag, "Current Day: " + getCurrentDayOfMonth());
String[] day_color = list.get(position).split("-");
String theday = day_color[0];
String themonth = day_color[2];
String theyear = day_color[3];
String completeDate = theday + "-" + themonth + "-" + theyear;
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null)) {
if (eventsPerMonthMap.containsKey(theday)) {
num_events_per_day = (TextView) row
.findViewById(R.id.num_events_per_day);
Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
if ((!eventsDaysPerMonthMap.isEmpty())
&& (eventsDaysPerMonthMap != null)) {
System.out.println("date in list is " + list.get(position));
if (eventsDaysPerMonthMap.containsKey(completeDate)) {
// row.setBackgroundColor(Color.GREEN);
gridcell.setBackgroundDrawable(getResources().getDrawable(
R.drawable.eventcalender));
// you can also use setBackground
}
}
// Set the Day GridCell
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-"
+ theyear);
if (day_color[1].equals("GREY")) {
gridcell.setTextColor(getResources()
.getColor(R.color.gray));
}
if (day_color[1].equals("WHITE")) {
gridcell.setTextColor(getResources().getColor(
R.color.Black));
}
if (day_color[1].equals("BLUE")) {
gridcell.setTextColor(getResources().getColor(R.color.white));
}
return row;
}
答案 0 :(得分:2)
但它显示28总是即最后一个按钮的gridview值
因为gridcell
保留了在getView
的最后一次调用时初始化的引用。
使用v
onClick
参数获取点击的按钮文字:
gridcell.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strvalue=((Button)v).getText().toString()
Toast.makeText(getActivity(),strvalue, Toast.LENGTH_LONG).show();
}
});