我有一个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。我怎样才能防止这种情况发生?
答案 0 :(得分: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 :(得分: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" />