Android setOnItemLongClickListener工作,但setOnItemClickListener不工作

Android setOnItemLongClickListener工作,但setOnItemClickListener不工作,android,Android,我一直在尝试创建一个应用程序,它使用网格来创建日历。 问题是setOnItemLongClickListener可以工作,但setOnItemClickListener不能,我不知道为什么会发生这种情况 CalendarView.java public class CalendarView extends LinearLayout { // for logging private static final String LOGTAG = "Calendar View";

我一直在尝试创建一个应用程序,它使用网格来创建日历。 问题是setOnItemLongClickListener可以工作,但setOnItemClickListener不能,我不知道为什么会发生这种情况

CalendarView.java

    public class CalendarView extends LinearLayout
{
    // for logging
    private static final String LOGTAG = "Calendar View";

    // how many days to show, defaults to six weeks, 42 days
    private static final int DAYS_COUNT = 42;

    // default date format
    private static final String DATE_FORMAT = "MMM yyyy";

    // date format
    private String dateFormat;

    // current displayed month
    private Calendar currentDate = Calendar.getInstance();

    //event handling
    private EventHandler eventHandler = null;
    final HashSet<Date> day_events=new HashSet<Date>();
    // internal components
    private LinearLayout header;
    private ImageView btnPrev;
    private ImageView btnNext;
    private TextView txtDate;
    private GridView grid;
    private TextView txtDay;
    // seasons' rainbow
    int[] rainbow = new int[] {
            R.color.summer,
            R.color.fall,
            R.color.winter,
            R.color.spring
    };

    // month-season association (northern hemisphere, sorry australia :)
    int[] monthSeason = new int[] {2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2};

    public CalendarView(Context context)
    {
        super(context);
    }

    public CalendarView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        initControl(context, attrs);
    }

    public CalendarView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        initControl(context, attrs);
    }

    /**
     * Load control xml layout
     */
    private void initControl(Context context, AttributeSet attrs)
    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.custom_calendar, this);

        loadDateFormat(attrs);
        assignUiElements();
        assignClickHandlers();

        updateCalendar();
    }

    private void loadDateFormat(AttributeSet attrs)
    {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CalendarView);

        try
        {
            // try to load provided date format, and fallback to default otherwise
            dateFormat = ta.getString(R.styleable.CalendarView_dateFormat);
            if (dateFormat == null)
                dateFormat = DATE_FORMAT;
        }
        finally
        {
            ta.recycle();
        }
    }
    private void assignUiElements()
    {
        // layout is inflated, assign local variables to components
        header = (LinearLayout)findViewById(R.id.calendar_header);
        btnPrev = (ImageView)findViewById(R.id.calendar_prev_button);
        btnNext = (ImageView)findViewById(R.id.calendar_next_button);
        txtDate = (TextView)findViewById(R.id.calendar_date_display);
        grid = (GridView)findViewById(R.id.calendar_grid);
//      grid.setLongClickable(true);
    //  grid.setClickable(true);

    }

    @SuppressLint("NewApi")
    private void assignClickHandlers()
    {

        // add one month and refresh UI
        btnNext.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                currentDate.add(Calendar.MONTH, 1);
                updateCalendar(day_events);
            }
        });

        // subtract one month and refresh UI
        btnPrev.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                currentDate.add(Calendar.MONTH, -1);
                updateCalendar(day_events);
            }
        });

        /*

        /*grid.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 Log.d(LOGTAG,"ITEM CLICK");
            }
        });*/

//nico
        grid.setOnItemClickListener(new OnItemClickListener()   { 
            @Override
            public void onItemClick(AdapterView<?> view, View cell,int position, long id) {

                  Object selected = grid.getItemAtPosition(position);
           //       Log.e("DEBUG", selected.toString())
                Log.d(LOGTAG,"ITEM CLICK");

        }
        });


        // long-pressing a day
        grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {

            @Override
            public boolean onItemLongClick(AdapterView<?> view, View cell, int position, long id)
            {
                // handle long-press
                if (eventHandler == null)
                    return false;

                eventHandler.onDayLongPress((Date)view.getItemAtPosition(position));
                Log.d(LOGTAG,"LONG ITEM CLICK");
                return true;
            }
        });
    }

    /**
     * Display dates correctly in grid
     */
    public void updateCalendar()
    {
        updateCalendar(null);
    }

    /**
     * Display dates correctly in grid
     */
    public void updateCalendar(HashSet<Date> events)
    {
        ArrayList<Date> cells = new ArrayList<Date>();
        Calendar calendar = (Calendar)currentDate.clone();

        // determine the cell for current month's beginning
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int monthBeginningCell = calendar.get(Calendar.DAY_OF_WEEK) - 1;

        // move calendar backwards to the beginning of the week
        calendar.add(Calendar.DAY_OF_MONTH, -monthBeginningCell);

        // fill cells
        while (cells.size() < DAYS_COUNT)
        {
            cells.add(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // update grid
        grid.setAdapter(new CalendarAdapter(getContext(), cells, events));

        // update title
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        txtDate.setText(sdf.format(currentDate.getTime()));

        // set header color according to current season
        int month = currentDate.get(Calendar.MONTH);
        int season = monthSeason[month];
        int color = rainbow[season];

        header.setBackgroundColor(getResources().getColor(color));
    }


    private class CalendarAdapter extends ArrayAdapter<Date>
    {
        // days with events
        private HashSet<Date> eventDays;

        // for view inflation
        private LayoutInflater inflater;

        public CalendarAdapter(Context context, ArrayList<Date> days, HashSet<Date> eventDays)
        {
            super(context, R.layout.custom_calendar_day, days);
            this.eventDays = eventDays;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View view, ViewGroup parent)
        {
            // day in question
            Date date = getItem(position);
            int day = date.getDate();
            int month = date.getMonth();
            int year = date.getYear();
            TextView tv_Date,tv_Event;
            grid.setOnItemClickListener(new  AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // TODO Auto-generated method stub
                    view.setBackgroundColor(Color.RED);
                    Date dt1=(Date)parent.getItemAtPosition(position);
                    day_events.add(dt1);
                    Log.d(LOGTAG,"ITEM CLICK");


                }
            });
            // today
            Date today = new Date();

            LinearLayout cell = (LinearLayout) (view == null
                    ? LayoutInflater.from(getContext()).inflate(R.layout.calendar_day, parent, false)
                            : view);
            tv_Date=((TextView)cell.findViewById(R.id.dayText));
            tv_Event=((EditText)cell.findViewById(R.id.dayEvent));

            // inflate item if it does not exist yet
            //  if (view == null)
            //  view = inflater.inflate(R.layout.calendar_day, parent, false);

            // if this day has an event, specify event image
            cell.setBackgroundResource(0);
            if (eventDays != null)
            {
                for (Date eventDate : eventDays)
                {
                    if (eventDate.getDate() == day &&
                            eventDate.getMonth() == month &&
                            eventDate.getYear() == year)
                    {
                        // mark this day for event
                        cell.setBackgroundColor(Color.RED);
                        break;
                    }
                }
            }

            // clear styling
            tv_Date.setTypeface(null, Typeface.NORMAL);
            tv_Date.setTextColor(Color.BLACK);

            if (month != today.getMonth() || year != today.getYear())
            {
                // if this day is outside current month, grey it out
                tv_Date.setTextColor(getResources().getColor(R.color.greyed_out));
            }
            else if (day == today.getDate())
            {
                // if it is today, set it to blue/bold
                tv_Date.setTypeface(null, Typeface.BOLD);
                tv_Date.setTextColor(getResources().getColor(R.color.today));
            }

            // set text
            tv_Date.setText(String.valueOf(date.getDate()));

            return cell;
        }
    }

    /**
     * Assign event handler to be passed needed events
     */
    public void setEventHandler(EventHandler eventHandler)
    {
        this.eventHandler = eventHandler;
    }

    /**
     * This interface defines what events to be reported to
     * the outside world
     */
    public interface EventHandler
    {
        void onDayLongPress(Date date);
    }
}
公共类日历视图扩展了LinearLayout
{
//用于记录
私有静态最终字符串LOGTAG=“日历视图”;
//显示多少天,默认为6周42天
私人静态最终整数天计数=42;
//默认日期格式
私有静态最终字符串日期\u格式=“MMM yyyy”;
//日期格式
私有字符串格式;
//当前显示月份
private Calendar currentDate=Calendar.getInstance();
//事件处理
私有EventHandler EventHandler=null;
final HashSet day_events=新HashSet();
//内部组件
专用线路布置头;
私人图像视图btnPrev;
私有图像视图btnNext;
私有文本视图txtDate;
私有网格视图;
私有文本视图txtDay;
//四季彩虹
int[]彩虹=新int[]{
R.color.summer,
R.color.fall,
R.color.winter,
R.color.spring
};
//月-季协会(北半球,澳大利亚:)
int[]monthSeason=newint[]{2,2,3,3,0,0,1,1,2};
公共日历视图(上下文)
{
超级(上下文);
}
公共日历视图(上下文、属性集属性)
{
超级(上下文,attrs);
initControl(上下文,attrs);
}
公共日历视图(上下文上下文、属性集属性、int-defStyleAttr)
{
super(上下文、attrs、defStyleAttr);
initControl(上下文,attrs);
}
/**
*负载控制xml布局
*/
私有void initControl(上下文上下文、属性集attrs)
{
LayoutFlater充气器=(LayoutFlater)context.getSystemService(context.LAYOUT\u充气器\u服务);
充气机。充气(R.layout.custom_日历,本);
loadDateFormat(attrs);
赋值元素();
赋值ClickHandlers();
updateCalendar();
}
私有void loadDateFormat(AttributeSet attrs)
{
TypedArray ta=getContext().ActainStyledAttributes(attrs,R.styleable.CalendarView);
尝试
{
//尝试加载提供的日期格式,否则返回默认值
dateFormat=ta.getString(R.styleable.CalendarView\u dateFormat);
如果(dateFormat==null)
dateFormat=日期\格式;
}
最后
{
ta.recycle();
}
}
私有void assignUiElements()
{
//布局膨胀时,将局部变量指定给组件
header=(LinearLayout)findViewById(R.id.calendar\u header);
btnPrev=(图像视图)findViewById(R.id.calendar\u prev\u按钮);
btnNext=(图像视图)findViewById(R.id.calendar\u next\u按钮);
txtDate=(TextView)findViewById(R.id.calendar\u date\u display);
grid=(GridView)findviewbyd(R.id.calendar\u grid);
//grid.setLongClickable(真);
//grid.setClickable(true);
}
@SuppressLint(“新API”)
私有void assignClickHandlers()
{
//添加一个月并刷新UI
setOnClickListener(新的OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
currentDate.add(日历月,1);
updateCalendar(日活动);
}
});
//减去一个月并刷新UI
setOnClickListener(新的OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
currentDate.add(日历月份,-1);
updateCalendar(日活动);
}
});
/*
/*grid.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
Log.d(LOGTAG,“项目点击”);
}
});*/
//尼科
grid.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共控件单击(AdapterView视图、视图单元格、整型位置、长id){
所选对象=grid.getItemAtPosition(位置);
//Log.e(“DEBUG”,selected.toString())
Log.d(LOGTAG,“项目点击”);
}
});
//漫长的一天
grid.setOnItemLongClickListener(新的AdapterView.OnItemLongClickListener()
{
@凌驾
公共布尔值长单击(AdapterView视图、视图单元格、整型位置、长id)
{
//长柄压力机
if(eventHandler==null)
返回false;
eventHandler.onDayLongPress((日期)视图.getItemAtPosition(位置));
Log.d(LOGTAG,“长项目点击”);
返回true;
}
});
}
/**
*在网格中正确显示日期
*/
public void updateCalendar()
{
updateCalendar(空);
}
/**
*在网格中正确显示日期
*/
public void updateCalendar(哈希集事件)
{
ArrayList单元格=新的ArrayList();
Calendar Calendar=(Calendar)currentDate.clone();
//确定当前月初的单元格
calendar.set(calendar.DAY\u/u月,1);
int monthBeginningCell=calendar.get(calendar.DAY\u OF\u WEEK)-1;
//将日历向后移动到周初
calendar.add(calendar.DAY,OF,OF,monthBeginingCell);
//填充单元格
while(cells.size()    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <!-- date toolbar -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="73dp"
        android:paddingBottom="12dp"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"
        android:paddingTop="12dp" >

        <ImageView
            android:id="@+id/calendar_prev_button"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:src="@drawable/prev_icon"
/>

        <ImageView
            android:id="@+id/calendar_next_button"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/calendar_prev_button"
            android:layout_marginRight="18dp"
            android:src="@drawable/next_icon"
   />

        <TextView
            android:id="@+id/calendar_date_display"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:text="current date"
            android:textAppearance="@android:style/TextAppearance.Medium"
            android:textColor="#222222"
 />

    </RelativeLayout>

    <!-- days header -->

    <LinearLayout
        android:id="@+id/calendar_header"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" 
 >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="MON"
            android:textColor="#222222"
  />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="TUE"
            android:textColor="#222222" 
        />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="WED"
            android:textColor="#222222"
    />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="THU"
            android:textColor="#222222"
  />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="FRI"
            android:textColor="#222222"
/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="SAT"
            android:textColor="#222222"
              />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="SUN"
            android:textColor="#222222"
             />
    </LinearLayout>

    <!-- days view -->

    <GridView
        android:id="@+id/calendar_grid"
        android:layout_width="wrap_content"
        android:layout_height="340dp"
        android:numColumns="7"
            >

    </GridView>

</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/dayText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.09"
        android:padding="2dp"
        android:scrollHorizontally="false"
        android:textColor="@android:color/black" />

    <EditText
        android:id="@+id/dayEvent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.06"
        android:ems="10"
        android:padding="2dp"
        android:scrollHorizontally="false"
        android:textColor="@android:color/black" />

</LinearLayout>
android:focusable="false"
android:focusableInTouchMode="false"