mGallery = findViewById(R.id.mygallery); mAdapeter = new GalleryAdapter(this); mGallery.setAdapter(mAdapeter); mGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mGallery.setSelection(position); Toast.makeText(GalleryActivity.this, "您点击了: " + position, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(GalleryActivity.this, ProgressBarActivity.class); startActivity(intent); GalleryActivity.this.finish(); } }); img1 = findViewById(R.id.himg1); img1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GalleryActivity.this, ProgressBarActivity.class); startActivity(intent); } }); } 将他改写为用HorizontalScrollView控件实现的代码
时间: 2024-03-03 16:47:51 浏览: 152
以下是将上述代码改写为使用HorizontalScrollView控件实现的示例代码:
```
mContainer = findViewById(R.id.container);
mInflater = LayoutInflater.from(this);
for (int i = 0; i < mImageIds.length; i++) {
View view = mInflater.inflate(R.layout.horizontal_item, mContainer, false);
ImageView imageView = view.findViewById(R.id.image);
imageView.setImageResource(mImageIds[i]);
mContainer.addView(view);
}
mContainer.setOnTouchListener(new View.OnTouchListener() {
private float mLastX;
private float mStartX;
private int mTouchSlop = ViewConfiguration.get(GalleryActivity.this).getScaledTouchSlop();
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastX = event.getX();
mStartX = mLastX;
break;
case MotionEvent.ACTION_MOVE:
float curX = event.getX();
float deltaX = curX - mLastX;
if (Math.abs(deltaX) > mTouchSlop) {
mContainer.scrollBy((int) -deltaX, 0);
mLastX = curX;
}
break;
case MotionEvent.ACTION_UP:
int distance = (int) (event.getX() - mStartX);
if (Math.abs(distance) < mTouchSlop) {
int index = (int) (event.getX() / mContainer.getWidth() * mImageIds.length);
Toast.makeText(GalleryActivity.this, "您点击了第 " + index + " 张图片", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(GalleryActivity.this, ProgressBarActivity.class);
startActivity(intent);
GalleryActivity.this.finish();
} else {
int targetIndex = (int) ((mContainer.getScrollX() + mContainer.getWidth() / 2) / mContainer.getWidth());
targetIndex = Math.max(0, Math.min(targetIndex, mImageIds.length - 1));
int scrollDistance = targetIndex * mContainer.getWidth() - mContainer.getScrollX();
mContainer.smoothScrollBy(scrollDistance, 0);
}
break;
}
return true;
}
});
```
在这个代码中,我们首先获取了一个放置图片的容器`mContainer`,然后使用LayoutInflater动态加载了每个图片的布局,并将它们添加到了容器中。接着,我们给容器设置了一个触摸事件监听器,实现了横向滑动的效果。当用户点击某张图片时,我们通过计算容器的滚动位置来确定用户点击的是哪张图片,并启动一个新的Activity。
阅读全文