2014-01-18 169 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" /> 
相關問題