1

我正在尝试制作一个带有选项的 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>

我试图使它易于理解,我希望你能理解我所做的正确。

如果您对更有效的方法有建议,我会很高兴听到。

谢谢!

4

0 回答 0