查看了网络上一些仿写微博时已选图片的展示的功能,感觉都为能达到自己的需求,或者局限性太大。作为一个合格的工程师在找不到好例子的时候就应该去自己定义一个View了。
根据直观的展示方式需要的是GridView,但是GridView的height不确定,设置为wrap_content时只显示单行的高度,需要滚动才能显示余下的。但是我要把GridView放在一个ScrollView中并把所有图片需要展示出来,GridView中的图片需要和其他View一起在ScrollView中滚动。
—ScrollView
—LinearLayout
—GridView
—other Views
首先展示一下代码:
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;
public class GalleryView extends GridView {
public GalleryView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public GalleryView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public GalleryView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec;
if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE , MeasureSpec.AT_MOST);
} else {
heightSpec = heightMeasureSpec;
}
super.onMeasure(widthMeasureSpec, heightSpec);
}
@Override
public void setOverScrollMode(int mode) {
// TODO Auto-generated method stub
super.setOverScrollMode(View.OVER_SCROLL_NEVER);
}
}
在onMeasure方法中加入部分代码,使height属性的值使用最大,及所谓的”match_parent“效果,该参数的意义是提供给onMeasure方法内部的参考高度,默认使用值,自定义的时候可用可不用。
但是在使用中发现,虽然GridView的height已经是最大值,所有图片显示出来了,但是在部分系统(FlymeOS)中有Scroll Hold功能,导致还是可以下拉隐藏下面的部分,为了能达到完全无法滚动,小编自寻其父类AbsListView的源码,在setOverScrollMode(mode)中有一个滚动模式设置
@Override
public void setOverScrollMode(int mode) {
if (mode != OVER_SCROLL_NEVER) {
if (mEdgeGlowTop == null) {
Context context = getContext();
mEdgeGlowTop = new EdgeEffect(context);
mEdgeGlowBottom = new EdgeEffect(context);
}
} else {
mEdgeGlowTop = null;
mEdgeGlowBottom = null;
}
super.setOverScrollMode(mode);
}
因为就是那个mode = OVER_SCROLL_NEVER时可以关闭其滚动功能,所以在自定义中复写该方法,只需要改动super中的参数。大功告成!!!
另外在GridView的item中加ImageView和一个删除小按钮的布局问题,直接贴代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="95dp"
android:layout_height="95dp" >
<ImageView
android:id="@+id/image"
android:layout_width="95dp"
android:layout_height="95dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:layout_centerInParent="true"
android:src="@drawable/icon" />
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_alignRight="@+id/image"
android:layout_alignTop="@+id/image"
android:src="@drawable/ic_delete" />
</RelativeLayout>
此处需要注意的是在GridView中展示时会有尺寸的调整,只会从需要绘制的x点和y点开始绘制
所以为了避免被影藏可以使用padding的属性来规避部分问题。