我正在开发一个Android应用程序,我需要创建一个自定义视图,并且必须在网格视图中重复填充该视图。
以下是我创建视图的代码段
<?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" >
<LinearLayout
android:id="@+id/layoutContent"
android:layout_width="80dp"
android:layout_height="80dp"
android:orientation="horizontal"
android:background="@drawable/navigationtextheaderbg">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
Gridview适配器如下所示,
class GridViewAdapter extends BaseAdapter{
Context c;
int[] imageResources;
String[] arrayTexts;
GridViewAdapter(Context x,int[] imageResourses, String[] array )
{
this.c=x;
this.imageResources=imageResourses;
this.arrayTexts=array;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return arrayTexts.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=View.inflate(c,R.layout.grid,null);
TextView tv1=(TextView)v.findViewById(R.id.textView1);
ImageView iv1=(ImageView)v.findViewById(R.id.imageView1);
tv1.setText(arrayTexts[position]);
iv1.setBackgroundResource(imageResources[position]);
return v;
}
}
我正在使用以下代码片段调用此适配器
GridView gridView=new GridView(MainActivity.this);
gridView.setNumColumns(4);
GridViewAdapter adapter=new GridViewAdapter(MainActivity.this,imageresources,arr1);
gridView.setAdapter(adapter);
这里 imageresourses&amp; arr1 分别是图像和字符串的数组。
int[] imageresources= new int[]{R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String[] arr1={"Ima","hello","yes","no"};
答案 0 :(得分:0)
您是否将GridView设置为contentView?
setContentView(gridView);
您应该将上面的XML文件设置为适配器类中的contentview。
View v=View.inflate(c,R.layout.grid,null);