如何修复我的onclick侦听器,以便在单击标题时不必单击两次以触发事件?

时间:2014-03-03 19:06:53

标签: android android-layout android-listview android-fragments android-fragmentactivity

我在我的代码中尝试onclick和onlongclick监听器。单击标题后,它应该触发A类并在长按单元格classB时触发。现在问题是,两者都相应地触发,但是对于第一次点击它没有做任何事情,但是第二次点击它可以正常工作。我究竟做错了什么?这是我的代码:

public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
....
frontpageHeader = view.findViewById(R.id.frontpage_header);
        ((TextView) frontpageHeader.findViewById(R.id.header_title)).setText(getActivity().getString(R.string.header_front_page));
        frontpageHeader.setOnClickListener(this);
...
}
@Override
    public void onClick(final View view) {
        switch (view.getId()) {
        case R.id.frontpage_header:
           frontpageHeader.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View vi) {
                    ((MainActivity) getActivity()).onNewsClicked(view);
                }

            });
            frontpageHeader.setOnLongClickListener(new OnLongClickListener() {   
                   @Override
                   public boolean onLongClick(View v) {

                       ManageNewsCategoriesActivity.newInstance(getActivity());                     
                    return true;
                   }
                  }); 
            break;
...

1 个答案:

答案 0 :(得分:3)

因为您在onClickListener内设置了onLongClickListeneronClick,为什么不在onCreateView中设置它们,基本上看起来像这样:

 public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
      frontpageHeader = view.findViewById(R.id.frontpage_header);

      frontpageHeader.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View vi) {
                ((MainActivity) getActivity()).onNewsClicked(view);
            }

        });
        frontpageHeader.setOnLongClickListener(new OnLongClickListener() {   
               @Override
               public boolean onLongClick(View v) {

                   ManageNewsCategoriesActivity.newInstance(getActivity());                     
                return true;
               }
        }); 
}