我正在尝试创建一个活动页面,该页面具有可滚动的gridview,它将显示图像,当我运行应用程序时我遇到了麻烦。图像没有显示,我不确定我错过了什么,以便他们显示当我从我的手机运行应用程序测试它我已经查找类似的教程,我已经基于我的代码关闭但它仍然无法正常工作。非常感谢任何帮助或输入,如果我需要提供任何其他代码,请告诉我。谢谢。
xml文件(activity_third.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="@+id/grid_view"
android:numColumns="2"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:smoothScrollbar="true"
>
</GridView>
</LinearLayout>
ThirdActivity.java
package com.example.firstapp2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
public class ThirdActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.third, menu);
return true;
}
}
ImageAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.balloon_1, R.drawable.balloon_2,
R.drawable.balloon_3, R.drawable.balloon_4,
R.drawable.balloon_5, R.drawable.balloon_6
/*insert array of images*/
};
}
答案 0 :(得分:0)
更改以下适配器类的方法。
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return position;
}
答案 1 :(得分:0)
您将返回 null 而不是数组位置。通过将其更改为
来检查一次public Object getItem(int position) {
return mThumbIds[position];
}