我是 android 编程的初学者,这是我在StackOverflow中的第一个问题。我有一个首选项片段,单击首选项时,我试图在对话框中显示网格视图。网格视图是动态加载的。我尝试了很多方法来做到这一点,但没有一个对我有用。
这是我在MyPreferenceFragment中扩展 PreferenceFragment的代码
Preference iconPref = (Preference)findPreference("pref_icon");
iconPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
Log.i(TAG, "Preparing grid view layout");
GridView gridview = (GridView)getActivity().findViewById(R.id.icons_gridview);
gridview.setAdapter(new ImageAdapter(getActivity()));
Log.i(TAG, "Icons image adapter ready");
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(getActivity(), "" + position, Toast.LENGTH_SHORT).show();
}
});
Log.i(TAG, "Creating dialog");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(gridview);
builder.show();
return false;
}
});
这是我的ImageAdapter.java代码
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) {
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.ic_img1, R.drawable.ic_img2,
R.drawable.ic_img3, R.drawable.ic_img4,
R.drawable.ic_img5, R.drawable.ic_img6,
R.drawable.ic_img7
};
}
最后,这是我的 XML 布局文件:icon_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/icons_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
我期待任何帮助或替代方案。并提前感谢...