使用android 写一个popwindow ,可以通过java代码中的图片资源id添加对应固定尺寸的图片,popwindow里的图片可以点击并可以进行回调,且里面的图片是横向排列
时间: 2024-05-15 08:15:05 浏览: 93
以下是一个实现该功能的示例代码:
1. 在布局文件中添加一个空的FrameLayout,用于显示PopWindow:
```xml
<FrameLayout
android:id="@+id/pop_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在Java代码中创建PopWindow,并设置其内容为一个横向排列的ImageView列表:
```java
// 获取PopWindow的布局
View popView = LayoutInflater.from(context).inflate(R.layout.pop_layout, null);
// 创建PopWindow,并设置宽高
PopWindow popWindow = new PopWindow.Builder(context)
.setView(popView)
.setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
.setFocusable(true)
.build();
// 获取ImageView列表的容器
LinearLayout container = popView.findViewById(R.id.container);
// 添加图片资源对应的ImageView
for (int i = 0; i < imageIds.length; i++) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIds[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new LinearLayout.LayoutParams(imageSize, imageSize));
imageView.setTag(i);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = (int) v.getTag();
// 点击图片后的回调
if (listener != null) {
listener.onImageClick(position);
}
popWindow.dismiss();
}
});
container.addView(imageView);
}
```
其中,imageIds为要显示的图片资源id数组,imageSize为每个图片的尺寸,listener为回调接口,onImageClick方法为点击图片后的回调方法。
3. 在回调接口中处理点击事件:
```java
public interface OnImageClickListener {
void onImageClick(int position);
}
...
// 创建PopWindow,并设置回调接口
PopWindowUtils.showImagePopWindow(context, imageIds, imageSize, new PopWindowUtils.OnImageClickListener() {
@Override
public void onImageClick(int position) {
// 处理点击事件
}
});
```
阅读全文
相关推荐


















