首页 新闻 会员 周边 捐助

关于用ViewHolder给GridView写适配器的问题

0
悬赏园豆:20 [待解决问题]
MainActivity的内容:
import
android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
private int[] pics = new int[] {
R.drawable.p1, R.drawable.p1, R.drawable.p1, R.drawable.p1,
R.drawable.p1, R.drawable.p1, R.drawable.p1, R.drawable.p1
};
private GridView grid_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid_view = (GridView) findViewById(R.id.grid_view);
MyAdapter adapter = new MyAdapter(this);
grid_view.setAdapter(adapter);
}
static class ViewHolder {
public ImageView img;
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public MyAdapter(Context context) {
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return pics.length;
}

@Override
public Object getItem(int position) {
return pics[position];
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item,null);
holder.img = (ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.img.setImageResource( pics[position]);
holder.img.setScaleType(ImageView.ScaleType.FIT_XY);
holder.img.setLayoutParams(new GridView.LayoutParams(300,200));
return convertView;
}
}
}
item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12sp"
android:id="@+id/img"/>
</LinearLayout>
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:padding="12sp" />
</LinearLayout>
为什么我用相似的方法写ListView的适配器可以,而写GridView的有错误(在模拟器上不能运行),望大神帮我看一看!!谢谢!
android小菜鸡的主页 android小菜鸡 | 初学一级 | 园豆:182
提问于:2017-03-15 17:10
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册