1

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