对于横向的GridView,很多人会说,没必要,用RecycleView就可以完成,但是,我就喜欢搞点特别的,因此当初就写了个横向的GridView。网上的东西大部分都有很多其它的东西,比如你要找一个功能,它会给你十个,然后你要去改,还不如自己写出来。。我的原则就是一切以简单为主。
主要代码:
DisplayMetrics dm =newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
floatdensity = dm.density;
intgridviewWidth = (int) (size * (length) * density);
intitemWidth = (int) (length * density);
LinearLayout.LayoutParams params =newLinearLayout.LayoutParams(
gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
mygridview.setLayoutParams(params);// 设置GirdView布局参数,横向布局的关键
mygridview.setColumnWidth(itemWidth);// 设置列表项宽
// gridsetRankPotentialActorGridViewView.setHorizontalSpacing(20); // 设置列表项水平间距
mygridview.setStretchMode(GridView.NO_STRETCH);
mygridview.setNumColumns(size);// 设置列数量=列表集合数
xml布局主要代码:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginBottom="10dp">
android:id="@+id/mygridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="auto_fit"
android:scrollbars="none"
android:stretchMode="spacingWidthUniform"/>
package demo.leo.com.horizontalgridview;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
/**
* Created by Leo on 2017/1/20.
*/
public class MyGridView extends GridView {
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGridView(Context context) {
super(context);
}
public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = widthMeasureSpec;
super.onMeasure(expandSpec, heightMeasureSpec);
}
}
packagedemo.leo.com.horizontalgridview;
importandroid.content.Context;
importandroid.view.View;
importandroid.widget.ImageView;
importandroid.widget.TextView;
importjava.util.HashMap;
importjava.util.Map;
/**
* Created by Leo on 2017/1/20.
*/
publicclassViewHolder{
publicViewconvertView;
publicstaticViewHoldergetVH(ViewconvertView,Contextcontent,intlayout)
{
if(convertView==null){
convertView=View.inflate(content,layout,null);
}
ViewHolderholder=newViewHolder(convertView);
returnholder;
}
// ImageView singlenews_iv;
// TextView title_tv;
// TextView time_tv;
publicMapmaps=newHashMap();
publicViewHolder(ViewconvertView)
{
this.convertView=convertView;
}
publicTgetView(intid)
{
if(maps.get(id)==null)
{
maps.put(id,convertView.findViewById(id));
}
return(T)maps.get(id);
}
publicTgetView(intid,Classclazz)
{
returngetView(id);
}
publicTextViewgetTv(intid)
{
returngetView(id,TextView.class);
}
publicImageViewgetIv(intid)
{
returngetView(id,ImageView.class);
}
}
csdn项目地址:http://blog.csdn.net/greatdaocaoren/article/details/54630266