为GridView android创建BaseAdapter

时间:2012-05-24 08:22:26

标签: android

基本上我需要创建: 左侧的复选框和右侧的图像视图。像这样:

enter image description here

纵向中的这些组合应为3xN,N为行数的int。为此,我认为使用网格视图会很好,但我对网格没有太多经验。所以我开始编写适配器:

我有这个方法:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    CheckBox check = null;
    ImageView pic = null;

    LinearLayout view = new LinearLayout(mContext);
    view.setOrientation(LinearLayout.VERTICAL);

        check = new CheckBox(mContext);
        check.setTag(position);

        view.addView(check); 

        pic = new ImageView(mContext);
        pic.setImageResource(R.drawable.btn_star);

        view.addView(pic); 


    return view;
} 

也许我应该创建一个复选框视图和图像视图。这工作但图像低于复选框,如何将它们组成一行?

感谢。

3 个答案:

答案 0 :(得分:2)

为gridview内容创建单独的布局例如:gridview_custom.xml

<?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="horizontal" android:gravity="center">

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>

</LinearLayout>

现在为GridView创建自定义适配器并覆盖getView()

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView; 
     CheckBox check = null;
             ImageView pic = null;


    if (convertView == null) { // if it's not recycled, initialize some
                                // attributes
    LayoutInflater vi = 
            (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.gridview_custom, null);
     } 

    pic = (ImageView)v.findViewById(R.id.imageView1);
    check = (CheckBox) v.findViewById(R.id.checkBox1);
    return v;

}

答案 1 :(得分:0)

由于布局是固定布局,因此在XML文件中指定布局并使用它来创建视图会更容易。不过,您应该使用HORIZONTAL方向。并且还要注意重新使用视图(在convertView参数中将一个可重用的实例传递给您。如果它不是null,请使用它。)

答案 2 :(得分:0)

不要动态添加复选框和图像。相反,你可以做的是,根据需要创建一个包含复选框和水平方向ImageView的XML文件,getView函数将是这样的:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (CONTEXT != null) {


        final LayoutInflater lInflater = (LayoutInflater) CONTEXT
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = lInflater.inflate(R.layout.your_xml, null);
        final CheckBox checkBox = (CheckBox) view
                .findViewById(R.id.checkbox);

        final ImageView ivIcon = (ImageView) view.findViewById(R.id.icon_image);
        ivIcon.setImageResource(A.this.getResources().getDrawables(R.id.image));
        return view;
        }
        else {
        return null;
        }
}

谢谢:)

相关问题