【问题标题】:Set OnTouchListener for Fragment为 Fragment 设置 OnTouchListener
【发布时间】:2013-12-15 07:28:33
【问题描述】:

我有一个包含多个片段的应用程序

对于每个片段,我想在触摸该片段时执行一些操作

我有一个为我绘制位图的片段,我希望这个片段在触摸时全屏显示 该片段有一个将其设置为位图的图像视图 我尝试在视图的片段内设置 OnTouchListener 但我不希望这样,因为每次用户在屏幕上按下它都会启动活动,即使它已经处于全屏状态 如何在片段的主要活动中添加 OnTouchListener

这是我的代码

主要活动中我正在这样做

 public class MainActivity extends Activity  {
                     DrawBitmap drawView;           
                     drawView = (DrawBitmap ) getFragmentManager().findFragmentById(R.id.drawid);

                    }

DrawBitmap 类中,这是我的 fragment

   public class DrawBitmap extends Fragment  {

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.imgid, container, true);

    v.setOnTouchListener(new View.OnTouchListener() {

        @Override
          public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
              switch(action){
                  case MotionEvent.ACTION_DOWN:

                      Intent intent = new Intent(getActivity(), SecondActivity.class);
                      startActivity(intent);
                              break;

              }

              return false;
          }

    });
    return v;


}

  }

SecondActivity

                public class SecondActivity extends Activity  {
                     DrawBitmap drawView;           
                     drawView = (DrawBitmap ) getFragmentManager().findFragmentById(R.id.drawid_full);

                    }

我希望能够在 Main Activity 中为 drawView 添加 OnTouchListener

【问题讨论】:

    标签: android android-fragments ontouchlistener start-activity


    【解决方案1】:

    片段不是视图,您不能直接在它们上添加这种侦听器。

    一种解决方案是覆盖“按键”样式的方法挂钩并抛出您自己的事件。不幸的是,片段也没有这个钩子。

    因此,最后一个应该完美工作的选项是将侦听器添加到您的片段在方法getView() 期间返回的视图(即片段的根视图)。然后,您将不得不在树视图层次结构中处理一些事件消耗,但它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      相关资源
      最近更新 更多