自定义view实现类似微信聊天查看大图效果
自定义View实现类似微信聊天查看大图效果
在微信聊天界面中,当用户点击图片时,会弹出一个全屏的图片预览界面。这个功能可以让用户方便地浏览和分享图片。下面我们将一步步地讲解如何使用自定义View实现类似微信聊天查看大图效果。
第一步:创建XML布局文件
首先,我们需要在res/layout目录下创建一个名为reply_view_pic.xml的XML布局文件。
```xml
android:layout_height="match_parent" android:orientation="vertical"> android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="centerCrop" /> android:layout_height="50dp" android:orientation="horizontal">
```
在这个XML布局文件中,我们定义了一个ImageView来显示图片,两个Button分别用于关闭和分享图片。
第二步:创建自定义View类
接下来,我们需要创建一个名为ReplyPicView.java的Java类来实现自定义View。
```javapublic class ReplyPicView extends FrameLayout {
private ImageView mIvPic;
private Button mBtnClose, mBtnShare;
public ReplyPicView(Context context) {
this(context, null);
}
public ReplyPicView(Context context, AttributeSet attrs) {
super(context, attrs);
View view = LayoutInflater.from(context).inflate(R.layout.reply_view_pic, this, true);
mIvPic = (ImageView) findViewById(R.id.iv_pic);
mBtnClose = (Button) findViewById(R.id.btn_close);
mBtnShare = (Button) findViewById(R.id.btn_share);
mBtnClose.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
dismiss();
}
});
mBtnShare.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
//分享图片逻辑 }
});
}
public void setPic(Bitmap bitmap) {
mIvPic.setImageBitmap(bitmap);
}
public void show() {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
getWindow().setAttributes(layoutParams);
getWindow().setBackgroundDrawableResource(R.drawable.bg_white);
getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}
public void dismiss() {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.width =0;
layoutParams.height =0;
getWindow().setAttributes(layoutParams);
}
}
```
在这个自定义View类中,我们实现了一个FrameLayout来显示图片和两个Button。我们还实现了几个方法来设置图片、显示和关闭。
第三步:使用自定义View
最后,我们需要在Activity中使用自定义View。
```javapublic class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReplyPicView replyPicView = new ReplyPicView(this);
replyPicView.setPic(BitmapFactory.decodeResource(getResources(), R.drawable.pic));
replyPicView.show();
setContentView(replyPicView);
}
}
```
在这个Activity中,我们创建了一个自定义View的实例,并设置了图片和显示了它。
通过以上步骤,我们实现了类似微信聊天查看大图效果的功能。