使用预先选择的项目创建可选GridView的最佳方法?

时间:2013-03-25 16:35:26

标签: android gridview

我正在尝试使用GridView选项来选择一个项目。必须预先选择GridView中的第一项。 我找到了一种方法来实现它并且它可以工作* ,但我认为有一种更有效的方法可以做到这一点。

  • 如果有人想要制作具有相同用途的GridView或ListView,此代码可以帮助您。它有效。

我的代码:

来自ImageAdapter的

getView():

public View getView(final int position, View convertView, ViewGroup parent) {
    final ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }
    // Sets the background for the first item (that should be pre-selected.
    if(position == 0) imageView.setBackgroundResource(Color.GRAY);

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

活动:

final GridView gridview = (GridView) view.findViewById(R.id.gridView);
gridview.setAdapter(new ImageAdapter(MainActivity.this));
gridview.setSelection(0);

gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    View previous = null; // The previous selected item
    boolean flag = true;
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                if(flag) { 
                /*
                * Checks if there is no selected item. 
                * If true (=until now nothing has been selected) 
                * it will set the first item as the "previously" selected one.
                */
                    previous = gridview.getChildAt(0); 
                    flag = false; 
                }
                if(previous != view) { 
                /* 
                * Checks if the current selected item has been already selected or no. 
                * If true (=new item selected) it will change 
                * the background of the new selected item.
                */

                    view.setBackgroundResource(Color.GRAY);
                    if(previous != view) previous.setBackgroundResource(0);
                    previous =  view; // Sets the "new" selected item as the previous one.
                }                   
            }
});

XML文件:

<GridView
    android:id="@+id/gridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="16dp"
    android:gravity="center"
    android:numColumns="4" >
</GridView>

我试图让它变得可以理解,我希望你能理解我做的正确。

如果您有更有效的方法,我会很高兴听到这一点。

谢谢!

0 个答案:

没有答案