获取按钮以在具有膨胀布局的画廊中工作

发布于 2024-11-07 17:32:55 字数 6087 浏览 0 评论 0原文

到目前为止,我拥有的是一个定制的画廊活动,其中我使用布局而不是图像来创建一个与 Android 主屏幕非常相似的可滑动用户界面。在我的应用程序中,这代表了用户可以通过滑动浏览的艺术品描述和图片的目录。
因为画廊消耗所有触摸事件,所以我创建了自己的画廊类的子类以允许滚动视图发挥作用。
我现在正在尝试向膨胀布局中的某些按钮添加功能。我认为这里又是画廊消耗触摸事件的问题,因为当在自定义的 baseAdapters getView 方法中的膨胀视图上设置 .setOnClickListener 时,什么也没有发生。我还尝试在通过 onItemSelectedListener 获取按钮后直接在膨胀布局中的按钮上设置 onClickListener,但结果是空指针异常。

这是初始化画廊的活动的代码:

public class CatalogueActivity extends Activity {   

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.catalogue_gallery);


    //initialize Gallery Widget
    MyGallery g = (MyGallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));

    g.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {  

            if(selectedItemView != null){

                switch (position){

                case 3:
                    //GoToMap Button in DetailView1
                    Button toMap_btn = (Button) selectedItemView.findViewById(R.id.GoToMap01);   
                    toMap_btn.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                          Intent toCatalogue = new Intent().setClassName("com.uart", "com.uart.uartMain");
                          toCatalogue.putExtra("tabContent", 71);
                          startActivity(toCatalogue);
                        }
                    });

                case 4:
                    //GoToMap Button in DetailView2
                    Button toMap_btn2 = (Button) selectedItemView.findViewById(R.id.GoToMap02);
                    toMap_btn2.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                          Intent toCatalogue = new Intent().setClassName("com.uart", "com.uart.uartMain");
                          toCatalogue.putExtra("tabContent", 72);
                          startActivity(toCatalogue);
                        }
                    });
                }

            }
        }


        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;

    private Integer[] mLayoutIds = {
            R.layout.cover,
            R.layout.catalogue_layout,
            R.layout.introduction,
            R.layout.artwork_detail,
            R.layout.artwork_detail2,
            R.layout.artwork_detail3,
            R.layout.artwork_detail4
    };

    public ImageAdapter(Context c) {
        mContext = c;
        TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
        mGalleryItemBackground = a.getResourceId(
                R.styleable.HelloGallery_android_galleryItemBackground, 0);
        a.recycle();
    }

    public int getCount() {
        return mLayoutIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = LayoutInflater.from(mContext).inflate(mLayoutIds[position], null);
        convertView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        convertView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              Intent toCatalogue = new Intent().setClassName("com.uart", "com.uart.uartMain");
              toCatalogue.putExtra("tabContent", 72);
              startActivity(toCatalogue);
            }
        });

        return convertView;
    }

}
}

这是我自定义的画廊子类:

public class MyGallery extends Gallery {

FriendlyScrollView currScrollView;
boolean isSwiping = false;

public MyGallery(Context ctx, AttributeSet attrSet) {
    super(ctx, attrSet);
    // TODO Auto-generated constructor stub
}

@Override
public boolean onTouchEvent(MotionEvent ev) {

    return super.onTouchEvent(ev);  
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    currScrollView = getCurrScrollView();

    return super.onInterceptTouchEvent(ev);     
}

private boolean myGestureDetection(float distanceX){
    if(distanceX >= 20 || distanceX <= -20){
        Log.i("myGallery", "distanceX = "+distanceX);
        isSwiping = true;
    }

    return isSwiping;
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

  if (myGestureDetection(distanceX) == false){
      if(currScrollView != null){
          currScrollView.scrollBy(0, (int) distanceY);
          Log.i("myGallery", "Is scrolling vertical");
      }
  } else{
      //Hier: Horizontal Scroll der Gallery Items
         Log.i("myGallery", "Is scrolling horizontal");
  }
  return super.onScroll(e1, e2, distanceX, distanceY);
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

    Log.i("myGallery", "is Swiping");
    isSwiping = false;

    // Calculate swipe-animation duration depending on gesture velocity
    float velMax = 2500f;
    float velMin = 1000f;
    float velX = Math.abs(velocityX);
    if (velX > velMax) {
      velX = velMax;
    } else if (velX < velMin) {
      velX = velMin;
    }
    velX -= 600;
    int k = 500000;
    int speed = (int) Math.floor(1f / velX * k);
    setAnimationDuration(speed);

    return true;     
}

private FriendlyScrollView getCurrScrollView() {
    int pos = getFirstVisiblePosition();
    if(pos != getAdapter().getCount()-1)
        return (FriendlyScrollView)this.getSelectedView();
    else
        return null;
}

}

现在的问题是,我是否必须再次覆盖画廊的 ontouch 事件? 我该怎么做?如果这是解决方案,我如何为膨胀布局中的每个按钮定义不同的功能(例如,通过意图启动新活动或跳转到目录中的不同“页面”)?

what i have until now is a customized gallery activity in which i inflate layouts instead of images to create a swipable ui quite similar to the android homescreen. In my application this represents a catalogue of descriptions and pictures of artworks the user can browse through by swiping.
Because gallery consumes all touchevents, i made my own subclass of the gallery class to allow scrollviews to function.
I´m now trying to add functionality to some buttons in the inflated layouts. I think here again is the problem that the gallery consumes the touchevents, because when setting a .setOnClickListener on the inflated View in the customized baseAdapters getView method nothing happens. I also tried to set an onClickListener directly on the Buttons in the inflated layouts after fetching them via an onItemSelectedListener, but the result is a null pointer exception.

Here is the code of the activity where the gallery is initialized:

public class CatalogueActivity extends Activity {   

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.catalogue_gallery);


    //initialize Gallery Widget
    MyGallery g = (MyGallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));

    g.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {  

            if(selectedItemView != null){

                switch (position){

                case 3:
                    //GoToMap Button in DetailView1
                    Button toMap_btn = (Button) selectedItemView.findViewById(R.id.GoToMap01);   
                    toMap_btn.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                          Intent toCatalogue = new Intent().setClassName("com.uart", "com.uart.uartMain");
                          toCatalogue.putExtra("tabContent", 71);
                          startActivity(toCatalogue);
                        }
                    });

                case 4:
                    //GoToMap Button in DetailView2
                    Button toMap_btn2 = (Button) selectedItemView.findViewById(R.id.GoToMap02);
                    toMap_btn2.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                          Intent toCatalogue = new Intent().setClassName("com.uart", "com.uart.uartMain");
                          toCatalogue.putExtra("tabContent", 72);
                          startActivity(toCatalogue);
                        }
                    });
                }

            }
        }


        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;

    private Integer[] mLayoutIds = {
            R.layout.cover,
            R.layout.catalogue_layout,
            R.layout.introduction,
            R.layout.artwork_detail,
            R.layout.artwork_detail2,
            R.layout.artwork_detail3,
            R.layout.artwork_detail4
    };

    public ImageAdapter(Context c) {
        mContext = c;
        TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
        mGalleryItemBackground = a.getResourceId(
                R.styleable.HelloGallery_android_galleryItemBackground, 0);
        a.recycle();
    }

    public int getCount() {
        return mLayoutIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = LayoutInflater.from(mContext).inflate(mLayoutIds[position], null);
        convertView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        convertView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              Intent toCatalogue = new Intent().setClassName("com.uart", "com.uart.uartMain");
              toCatalogue.putExtra("tabContent", 72);
              startActivity(toCatalogue);
            }
        });

        return convertView;
    }

}
}

And here is my customized gallery subclass:

public class MyGallery extends Gallery {

FriendlyScrollView currScrollView;
boolean isSwiping = false;

public MyGallery(Context ctx, AttributeSet attrSet) {
    super(ctx, attrSet);
    // TODO Auto-generated constructor stub
}

@Override
public boolean onTouchEvent(MotionEvent ev) {

    return super.onTouchEvent(ev);  
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    currScrollView = getCurrScrollView();

    return super.onInterceptTouchEvent(ev);     
}

private boolean myGestureDetection(float distanceX){
    if(distanceX >= 20 || distanceX <= -20){
        Log.i("myGallery", "distanceX = "+distanceX);
        isSwiping = true;
    }

    return isSwiping;
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

  if (myGestureDetection(distanceX) == false){
      if(currScrollView != null){
          currScrollView.scrollBy(0, (int) distanceY);
          Log.i("myGallery", "Is scrolling vertical");
      }
  } else{
      //Hier: Horizontal Scroll der Gallery Items
         Log.i("myGallery", "Is scrolling horizontal");
  }
  return super.onScroll(e1, e2, distanceX, distanceY);
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

    Log.i("myGallery", "is Swiping");
    isSwiping = false;

    // Calculate swipe-animation duration depending on gesture velocity
    float velMax = 2500f;
    float velMin = 1000f;
    float velX = Math.abs(velocityX);
    if (velX > velMax) {
      velX = velMax;
    } else if (velX < velMin) {
      velX = velMin;
    }
    velX -= 600;
    int k = 500000;
    int speed = (int) Math.floor(1f / velX * k);
    setAnimationDuration(speed);

    return true;     
}

private FriendlyScrollView getCurrScrollView() {
    int pos = getFirstVisiblePosition();
    if(pos != getAdapter().getCount()-1)
        return (FriendlyScrollView)this.getSelectedView();
    else
        return null;
}

}

The question now is, do i again have to override the gallery´s ontouch events?
How would i do this? And if this is the solution, how can i define different functionalities for every button in the inflated layouts (eg. start a new activity via intent or jump to a different "page" in the catalogue)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文