2015-01-29 2 views
0

У меня есть небольшая проблема с gridview, ямки показывают нормально, но когда я прокручиваю вниз, я прокручиваю изображение, меняя положение изображения или повторяю, я не знаю, почему я немного запутался, я использую более 50-100 изображений, но теперь только 19 изображений, которые я тестировал, как это будет, я получил эту проблему, и она не будет придерживаться ее позиции. Спасибо.Android GridView Repeating Images

public class ImageAdapter extends BaseAdapter { 
private Context context; 


public Integer[] images = { 
     R.drawable.f_alicate,R.drawable.f_arcoajustable, 
     R.drawable.f_bateria,R.drawable.f_bisagra, 
     R.drawable.f_bisagra2,R.drawable.f_cadena_galvanizada, 
     R.drawable.f_canilla_bronze ,R.drawable.f_canilla_con_palanca, 
     R.drawable.f_casco_rojo,R.drawable.f_casco_rojo2, 
     R.drawable.f_cerraduracajon,R.drawable.f_cerradura_para_cajon2, 
     R.drawable.f_conexion_cromado,R.drawable.f_cotra_candena, 
     R.drawable.f_cuchara_albanil,R.drawable.f_cutter, 
     R.drawable.f_cutter2,R.drawable.f_disco, 
     R.drawable.f_corta_hiero}; 

// Constructor 
public ImageAdapter(Context c){ 
    context = c; 
} 

public int getCount() { 
    return images.length; 
} 

public Object getItem(int position) { 
    return images[position]; 
} 

public long getItemId(int position) { 
    return position; 
} 

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

    ImageView imageView = null ; 

     if (convertView == null) { 
      imageView = new ImageView(context); 
      new BitmapWorkerTask(imageView).execute(images[position]); 

      //create new ImageView if it is not present and populate it with some image 
     } else { 
      imageView = (ImageView) convertView; 
      //re-use ImageView that already exists in memory 
     } 
    return imageView; 
} 


class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> { 
    private final WeakReference<ImageView> imageViewReference; 
    private int data = 0; 

    public BitmapWorkerTask(ImageView imageView) { 
     // Use a WeakReference to ensure the ImageView can be garbage collected 
     imageViewReference = new WeakReference<ImageView>(imageView); 
    } 

    // Decode image in background. 
    @Override 
    protected Bitmap doInBackground(Integer... params) { 
     data = params[0]; 
     return decodeSampledBitmapFromResource(ImageAdapter.this.context.getResources(), data, 450, 450); 
    } 

    // Once complete, see if ImageView is still around and set bitmap. 
    @Override 
    protected void onPostExecute(Bitmap bitmap) { 
     if (imageViewReference != null && bitmap != null) { 
      final ImageView imageView = imageViewReference.get(); 
      if (imageView != null) { 
       imageView.setImageBitmap(bitmap); 
       imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
       imageView.setLayoutParams(new GridView.LayoutParams(450, 450)); 
      } 
     } 
    } 
} 

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 
                int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeResource(res, resId, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeResource(res, resId, options); 
} 

public static int calculateInSampleSize(
     BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     // Calculate ratios of height and width to requested height and width 
     final int heightRatio = Math.round((float) height/(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 

     // Choose the smallest ratio as inSampleSize value, this will guarantee 
     // a final image with both dimensions larger than or equal to the 
     // requested height and width. 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
    } 

    return inSampleSize; 
} 

}

+0

Поскольку похоже, что вы отправляете асинхронные запросы для захвата изображений, и из того, что я вижу в приведенном выше коде, вы не отменяете запросы при повторном просмотре, это может вызвать проблему, которую вы видите. Однако, так как некоторые из кода являются // seudo-кодом, трудно сказать наверняка. – Submersed

ответ

2

В GetView(), при повторном использовании ImageView, что уже существует вам все еще нужно установить образ этой точки зрения. На самом деле вы устанавливаете изображение, когда оно является только новым ImageView.

0
public View getView(int position, View convertView, ViewGroup parent) { 
    View v; 
    if (convertView == null) { // if it's not recycled, initialize some attributes 
     LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); 
     v = inflater.inflate(R.layout.gridview_item_layout, parent, false); 
    } else { 
     v = (View) convertView; 
    } 
    TextView text = (TextView)v.findViewById(R.id.grid_item_text); 
    text.setText(mTextIds[position]); 
    ImageView image = (ImageView)v.findViewById(R.id.grid_item_image); 
    image.setImageDrawable(mThumbIds[position]); 
    return v; 
} 
0

попробовать этот основной фрагмент

public class Fragment_Main_Dashboard extends Fragment { 
GridView dashbord_icon; 


List<ItemObj_for_Dashbord_list> dashbord_list1 = getAllItemObject(); 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.fragment_dashbord_alert_list, container, false); 
    setHasOptionsMenu(true); 
    getActivity().setTitle("Dashboard"); 

    Intent intent = new Intent(getActivity(), Service_for_login_check.class); 
    getActivity().startService(intent); 

    dashbord_icon = (GridView) view.findViewById(R.id.dashboard_icon); 


    Custom_Adapter_Dashboard_grid adapter1 = new Custom_Adapter_Dashboard_grid(getActivity(), dashbord_list1); 
    dashbord_icon.setAdapter(adapter1); 


    dashbord_icon.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      Object o = dashbord_icon.getItemAtPosition(position); 


      if (position == 0) { 
       Fragment fragment = new Fragment_Main_Advance_tracking(); 
       FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.texeting_fram, fragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 
      } else if (position == 1) { 
       Fragment fragment = new Fragment_Main_Vehicle_Status(); 
       FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.texeting_fram, fragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 
      } else if (position == 2) { 
       Intent All_veickle = new Intent(getActivity(), Activity_Drawer_Dashboard.class); 
       Boolean key = true; 
       All_veickle.putExtra("total_veickle", key); 

       startActivity(All_veickle); 
       getActivity().finish(); 

      } else if (position == 3) { 


       Fragment fragment = new Fragment_Main_Alerts(); 
       FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.texeting_fram, fragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 


      } else if (position == 4) { 
       Fragment fragment = new Fragment_Main_VEHICLE_Setting(); 
       FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.texeting_fram, fragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 

      } else { 
       Fragment fragment = new Fragment_Main_Support(); 
       FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.texeting_fram, fragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 


      } 


     } 


    }); 


    return view; 
} 


private List<ItemObj_for_Dashbord_list> getAllItemObject() { 
    List<ItemObj_for_Dashbord_list> items = new ArrayList<>(); 
    items.add(new ItemObj_for_Dashbord_list(R.drawable.dashbord_icon1, "ADVANCE TRACKING", 0)); 
    items.add(new ItemObj_for_Dashbord_list(R.drawable.dashbord_icon2, "VEHICLE STATUS", 0)); 

    items.add(new ItemObj_for_Dashbord_list(R.drawable.dashbord_icon4, "TOTAL VEHICLES", 0)); 
    items.add(new ItemObj_for_Dashbord_list(R.drawable.dashbord_icon3, "ALERTS", 0)); 
    items.add(new ItemObj_for_Dashbord_list(R.drawable.dashbord_icon5, "VEHICLE SETTINGS", 0)); 
    items.add(new ItemObj_for_Dashbord_list(R.drawable.dashbord_icon6, "SUPPORT", 0)); 


    return items; 
} 

//****************this is for inflatting nodification count funtionality 
public Drawable buildCounterDrawable(int count, int backgroundImageId, Context context) { 
    LayoutInflater inflater = LayoutInflater.from(context); 
    View view = inflater.inflate(R.layout.menu_counter_menuitem_layout, null); 
    view.setBackgroundResource(backgroundImageId); 

    if (count == 0 || count >= 100) { 
     View counterTextPanel = view.findViewById(R.id.counterValuePanel); 
     counterTextPanel.setVisibility(View.GONE); 
    } else { 
     TextView textView = (TextView) view.findViewById(R.id.count); 
     textView.setText("" + count); 
    } 

    view.measure(
      View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 
      View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 

    view.setDrawingCacheEnabled(true); 
    view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); 
    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); 
    view.setDrawingCacheEnabled(false); 

    return new BitmapDrawable(getResources(), bitmap); 
} 


@Override 
public void onCreateOptionsMenu(
     Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.menu_main, menu); 
    menu.clear(); 

    MenuItem item = 
      menu.add(Menu.FIRST, R.id.dashboard_nodifycation, 3, "NODIFICATION"); 
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 
    menu.add(Menu.FIRST, R.id.System_log, 4, "LOGOUT"); 

    Database_for_GCM_data dbHelper = null; 
    dbHelper = new Database_for_GCM_data(getActivity()); 
    int unread_count = Integer.parseInt(dbHelper.getUnreadCount()); 
    // calling function for nodification inflater 
    item.setIcon(buildCounterDrawable(unread_count, R.drawable.white_nodification, getActivity())); 


} 

}

фрагмент XML макет

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center"> 

    <GridView 
     android:id="@+id/dashboard_icon" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:background="#ffffff" 
     android:columnWidth="90dp" 
     android:focusable="false" 
     android:focusableInTouchMode="false" 
     android:gravity="center" 
     android:horizontalSpacing="1dp" 
     android:numColumns="2" 
     android:stretchMode="columnWidth" 
     android:verticalSpacing="1dp"></GridView> 
</LinearLayout> 

пользовательский адаптер

public class Custom_Adapter_Dashboard_grid extends BaseAdapter { 

private LayoutInflater layoutinflater; 
private List<ItemObj_for_Dashbord_list> listStorage; 
private Context context; 

public Custom_Adapter_Dashboard_grid(Context context, List<ItemObj_for_Dashbord_list> customizedListView) { 
    this.context = context; 
    try { 


     layoutinflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     listStorage = customizedListView; 
    } catch (Exception e) { 

    } 
} 

@Override 
public int getCount() { 

    return listStorage.size(); 
} 

@Override 
public Object getItem(int position) { 
    return position; 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

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

    ViewHolder listViewHolder; 
    if (convertView == null) { 

     listViewHolder = new ViewHolder(); 
     convertView = layoutinflater.inflate(R.layout.custom_adapter_dashbord_grid_list, parent, false); 
     listViewHolder.screenShot = (ImageView) convertView.findViewById(R.id.icon_image); 

     listViewHolder.musicName = (TextView) convertView.findViewById(R.id.icon_name); 


     convertView.setTag(listViewHolder); 
    } else { 
     listViewHolder = (ViewHolder) convertView.getTag(); 
    } 
    listViewHolder.screenShot.setImageResource(listStorage.get(position).getimage()); 
    listViewHolder.musicName.setText(listStorage.get(position).geticonName()); 


    return convertView; 
} 

static class ViewHolder { 
    ImageView screenShot; 
    TextView musicName; 

} 

} пользовательский макет адаптер

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:card_view="http://schemas.android.com/apk/res-auto" 
android:id="@+id/card_view" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
card_view:cardCornerRadius="2dp" 
card_view:cardElevation="2dp" 
card_view:cardUseCompatPadding="true"> 

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:orientation="vertical" 
    android:padding="8dp"> 

    <ImageView 
     android:id="@+id/icon_image" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_gravity="center_horizontal" 
     android:contentDescription="@string/hello_world" 
     android:scaleType="centerCrop" /> 

    <TextView 
     android:id="@+id/icon_name" 
     android:layout_width="wrap_content" 
     android:layout_height="30dp" 
     android:layout_below="@+id/icon_image" 
     android:layout_gravity="center_horizontal" 
     android:layout_marginTop="8dp" 
     android:gravity="center_horizontal" 
     android:text="sample" 
     android:textSize="12sp" /> 
</LinearLayout> 

вещь OBJ

public class ItemObj_for_Dashbord_list { 

private int dashbord; 
private String iconname1; 
String unread; 


public ItemObj_for_Dashbord_list(int screenShot, String iconname, int unreadcound) { 
    dashbord = screenShot; 
    iconname1 = iconname; 
    unread = String.valueOf(unreadcound); 

} 

public int getimage() { 
    return dashbord; 
} 

public String geticonName() { 
    return iconname1; 
} 

public String getunreadcount() { 
    return unread; 
} 

}