2014-01-18 173 views
0

我有一个由安装在设备上的所有应用程序填充的GridView。用户可以在这里选择某些应用程序。我希望选定的应用程序不透明并且未被选择为部分透明。我做了以下几点:当点击元素时,防止GridView重置滚动到顶部?

public View getView(int position, View convertView, ViewGroup parent) { 
    LinearLayout linearLayout = new LinearLayout(mContext); 
    linearLayout.setOrientation(LinearLayout.VERTICAL); 
    linearLayout.setGravity(Gravity.CENTER_HORIZONTAL); 
    LinearLayout.LayoutParams layoutParamsText = new LinearLayout.LayoutParams(150, 90); 

    ImageView imageView = new ImageView(mContext); 
    TextView appLabel = new TextView(mContext); 
    final OurAppInfo info = (OurAppInfo) getItem(position); 

    if(!installedApplications.contains(info)){ 
     AlphaAnimation alpha = new AlphaAnimation(0.4F, 0.4F); 
     alpha.setDuration(0); 
     alpha.setFillAfter(true); 
     linearLayout.startAnimation(alpha); 
    } 

    String appName = info.label; 
    if (appName.length() > 25) { 
     appName = appName.substring(0, 25); 
     appName = appName + "..."; 
    } 
    appLabel.setText(appName); 
    appLabel.setTextColor(Color.BLACK); 
    appLabel.setGravity(Gravity.CENTER_HORIZONTAL); 
    appLabel.setTypeface(null, Typeface.BOLD); 

    imageView.setImageDrawable(info.drawableAppIcon); 
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    imageView.setLayoutParams(new GridView.LayoutParams(110, 110)); 
    appLabel.setTextSize(15); 

    linearLayout.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if (installedApplications.contains(info)){ 
       installedApplications.remove(info); 
       receiveUpdate(installedApplications, false, false); 
      } else { 
       installedApplications.add(info); 
       Collections.sort(installedApplications); 
       receiveUpdate(installedApplications, false, false); 
      } 
     } 
    }); 

    appLabel.setLayoutParams(layoutParamsText); 

    linearLayout.addView(imageView); 
    linearLayout.addView(appLabel); 

    return linearLayout; 
} 

这是GridAdapter extends BaseAdapter的一部分。代码按预期工作,当我点击一个应用程序时,它会从列表中删除或添加到列表中,并根据透明度进行设置。但是,每当我点击GridView中的一个元素时,该视图就会重置,并被带到可滚动的GridView的顶部。显然,这对于少数应用程序来说不是问题,但是如果您选择的是XYZ字母附近的应用程序,则每次选择一个应用程序时,您都会被带回ABC。我怎样才能防止这种情况发生?

回答

1

看起来您正在刷新适配器,只要您进行更改,使网格回到初始位置。在对适配器进行任何更改之前,您可以尝试保存并恢复位置。

//Before refreshing the adapter you get both X and Y position 
int xPos = grid.getScrollX(); 
int yPos = grid.getScrollY(); 

然后你更新你的适配器。

适配器重新恢复你的发车位置后:

grid.scrollTo(xPos, yPos); 

您也可以使用(每次可能的)方法notifyDataSetChanged(),而不是创建一个新的适配器。

希望它有帮助。

1

检查所有子视图的自动高度或宽度。 我猜gridview计算这个视图的大小,每当你改变数据。 这是我的情况的解决方案。

在我的情况下改变了这个:

<ImageView 
    android:id="@+id/image" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

要这样:

<ImageView 
    android:id="@+id/image" 
    android:layout_width="100dp" 
    android:layout_height="100dp" /> 
相关问题