我在我的应用程序中使用具有三列的 GridView。你可以在下面看到它。
<GridView
android:id="@+id/mainMenu"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:columnWidth="60dp"
android:gravity="center"
android:numColumns="3"
android:stretchMode="columnWidth"
android:horizontalSpacing="1dp"
android:verticalSpacing="1dp" >
动态地,我想在 GridView 中的六个不同位置放置 6 个图像。我在这方面开发了一些代码,每次运行代码时,它都会将图像放置在错误的位置。实际上我想把 image_1 放在 position_0 上,把 image_2 放在 position_1 上,把 image_3 放在 position_2 上等等。我怎样才能完成预期的任务。请在这方面帮助我,我会非常感谢你的善举。提前致谢。
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.main);
grdMainMenu = (GridView) findViewById(R.id.mainMenu);
grdMainMenu.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter
{
Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
@Override
public int getCount()
{
// TODO Auto-generated method stub
return 6;
}
@Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v;
ImageView iv;
if(convertView ==null)
{
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
iv = (ImageView)v.findViewById(R.id.icon_image);
if(position == 0)
{
iv.setImageResource(R.drawable.image1);
}
if(position == 1)
{
iv.setImageResource(R.drawable.image2);
}
if(position == 2)
{
iv.setImageResource(R.drawable.image3);
}
if(position == 3)
{
iv.setImageResource(R.drawable.image4);
}
if(position == 4)
{
iv.setImageResource(R.drawable.image5);
}
if(position == 5)
{
iv.setImageResource(R.drawable.image6);
}
}
else
{
v = convertView;
}
return v;
}