2017-06-06 69 views
0

我有一個網格視圖中,這是我如何實現它的Android的GridView錯誤,顯示最後一個項目不正確

<GridView 
    android:horizontalSpacing="8dp" 
    android:verticalSpacing="8dp" 
    android:id="@+id/homeGrid" 
    android:layout_width="wrap_content" 
    android:layout_height="0dp" 
    android:layout_marginLeft="15dp" 
    android:layout_marginRight="15dp" 
    android:layout_marginTop="15dp" 
    android:layout_weight="3" 
    android:numColumns="auto_fit" /> 

,其目的是顯示使用定製適配器7項,並且這是怎麼實現的適配器

private Context mContext; 
private final String[] item; 
private final int[] imageId; 

public GridAdapter(Context c, String[] item, int[] imageId) { 
    mContext = c; 
    this.item = item; 
    this.imageId = imageId; 
} 

@Override 
public int getCount() { 
    return item.length; 
} 

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

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

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

    LayoutInflater inflater = (LayoutInflater) mContext 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    if (convertView == null) { 
     grid = inflater.inflate(R.layout.home_grid_layout, null); 
     TextView textView = (TextView) grid.findViewById(R.id.grid_text); 
     ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image); 
     textView.setText(item[position]); 
     imageView.setImageResource(imageId[position]); 
    } else { 
     grid = convertView; 
    } 
    return grid; 

} 

}

,然後我開始在我的活動這樣

GridAdapter adapter = new GridAdapter(HomePage.this, title, imageId); GridView grid = (GridView) findViewById(R.id.homeGrid);

的問題是,在顯示最後一個位置,這是因爲位置0 6位應用程序,strangly我實現onitemclicklistener我的GridView和我有當我點擊的最後一個位置的正確位置。

我的錯誤在哪裏?

+0

您的適配器是好的,把你的onItemClick代碼。 –

回答

0

試試看看這個代碼。

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

    LayoutInflater inflater = (LayoutInflater) mContext 
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    if (convertView == null) { 
     convertView = inflater.inflate(R.layout.home_grid_layout, null); 
    } 

    TextView textView = (TextView) convertView.findViewById(R.id.grid_text); 
    ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_image); 

    textView.setText(item[position]); 
    imageView.setImageResource(imageId[position]); 

    return convertView; 

} 
+0

真棒它工作.. –

相關問題