在开发中可能你需要一个2*2,或者3*3,N*N的布局,但是又不会涉及到滑动,此时可以自定义一个不需要滑动的网格布局。
public class UserTopicGridView extends RelativeLayout{
private Context mContext;
private Activity mActivity;
private String title;
private TApplication mTApplication;
private int columnLine = 2;
private int childWidth = 100;
private int childHeight = 100;
private int horSpace = 10;
private int verSpace = 10;
public UserTopicGridView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
mActivity = (Activity) this.mContext;
mTApplication = (TApplication) mActivity.getApplication();
}
public void setTitle(String title) {
this.title = title;
}
public void setChildSize(int width ,int height) {
this.childWidth = width;
this.childHeight = height;
requestLayout();
}
public void setPadding(int horSpace, int verSpace) {
this.horSpace = horSpace;
this.verSpace = verSpace;
requestLayout();
}
public void initViews(final HomeListBean homeListBean) {
List <Object> list = homeListBean.items;
for(int i = 0; i < list.size(); i++) {
ImageView imageView = new ImageView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(childWidth, childHeight);
imageView.setLayoutParams(params);
imageView.setScaleType(ScaleType.FIT_XY);
ImageLoader.getInstance().displayImage((String)list.get(i), imageView, mTApplication.getOptions());
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do something
}
});
addView(imageView);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
int childWidthMeasureSpec = MeasureSpec
.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);
int childheightMeasureSpec = MeasureSpec
.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);
View child = getChildAt(i);
child.measure(childWidthMeasureSpec, childheightMeasureSpec);
}
int newParentWidth = childWidth * columnLine + horSpace * (columnLine - 1);
int newParentHeight = childHeight * getLine() + verSpace * (getLine() - 1);
setMeasuredDimension(newParentWidth, newParentHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int left = 0;
int top = 0;
for(int i = 0; i < childCount; i++) {
if(isNewLine(i)) {
top += childHeight + verSpace;
left = 0;
}
View view = getChildAt(i);
view.layout(left, top, left + childWidth, childHeight + top);
left += childWidth + horSpace;
}
}
private boolean isNewLine(int index) {
if(index !=0 && index % columnLine == 0) {
return true;
}
return false;
}
private int getLine() {
int line = 0;
line = getChildCount() / 2;
if(getChildCount() % columnLine != 0) {
line += 1;
}
return line;
}
}
第一篇博客,略显粗糙,没有注释,但是相信大家都会懂,晚安。
1074

被折叠的 条评论
为什么被折叠?



