我正在开发一个 Android 应用程序,我需要在其中创建一个自定义视图,并且必须在 Grid View 中重复填充该视图。
这是我用于创建视图的代码片段
<?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 & 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"};