我是android新手。我想基于总行数和列构建网格并在视图中显示。创建网格后,我需要在其中一个网格中放置图标。该图标将来自服务器URL。网格应如下所示。
创建的网格应该适合屏幕。我怎么做?有人可以给我一个代码示例。在此先感谢!!!
答案 0 :(得分:1)
res / layout / gridview_android_example_with_image.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/gridview_android_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:columnWidth="100dp"
android:gravity="center"
android:minHeight="90dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
AndroidGridViewDisplayImages.java
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class AndroidGridViewDisplayImages extends AppCompatActivity {
GridView androidGridView;
// Dummy Array of images (Replace with your own values)
Integer[] imageIDs = {
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_android_example_with_image);
androidGridView = (GridView) findViewById(R.id.gridview_android_example);
androidGridView.setAdapter(new ImageAdapterGridView(this));
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getBaseContext(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
}
});
}
public class ImageAdapterGridView extends BaseAdapter {
private Context mContext;
public ImageAdapterGridView(Context c) {
mContext = c;
}
public int getCount() {
return imageIDs.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView mImageView;
if (convertView == null) {
mImageView = new ImageView(mContext);
mImageView.setLayoutParams(new GridView.LayoutParams(130, 130));
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setPadding(16, 16, 16, 16);
} else {
mImageView = (ImageView) convertView;
}
mImageView.setImageResource(imageIDs[position]);
return mImageView;
}
}
}