Note: This problem only happens in gridview, if you setimagebitmap in a single imageview, it works well.
See the following pictures, The left picture is what I want, and the picture on right is what actually I get.
The only difference is the way I set the image, if I set the image as below, I get the correct result(left picture above).
holder.image.setImageResource(imagesArray.get(position));
But if I set the image with bitmap as below, the image not scaled as I want(the right picture above)
holder.imageView.setImageBitmap(bitmap);
Why I set the image as bitmap instead of drawable?
because my images were encrypted, I need to decrypt them before load into the imageview. the basic step is:
depryct the image into byte arrya.
create bitmap from the bytes.
load the bitmap into imageview.
Note, the problem was not caused by the decryption, I have test with an normal image without decryption, it does not work either.
Here is the code
GridViewActivity
public class GridViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
GridView gridView = (GridView)findViewById(R.id.grid_view);
ImageAdapter imageAdapter = ImageAdapter.getInstance();
imageAdapter.setContext(this);
gridView.setAdapter(imageAdapter);
for (int i = 0; i < 50; i++) {
int resourceId = getResources().getIdentifier("myimage", "drawable", getPackageName());
imageAdapter.imagesArray.add(resourceId);
}
}
}
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private static ImageAdapter imageAdapter = null;
private Bitmap bitmap;
private Context mContext;
public ArrayList<Integer> imagesArray = new ArrayList<Integer>();
private ImageAdapter() {
}
public static ImageAdapter getInstance() {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter();
}
return imageAdapter;
}
public void setContext(Context context) {
mContext = context;
}
#Override
public int getCount() {
return imagesArray.size();
}
#Override
public Object getItem(int position) {
return imagesArray.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
row = inflater.inflate(R.layout.row_grid, parent, false);
holder = new ViewHolder();
holder.imageView = (ImageView)row.findViewById(R.id.image);
row.setTag(holder);
}
else {
holder = (ViewHolder)row.getTag();
}
// Create bitmap from image in assets folder.
String imageFileName = "myimage.jpg";
AssetManager assetMgr = mContext.getAssets();
try {
InputStream fis = assetMgr.open(imageFileName);
bitmap = BitmapFactory.decodeStream(fis);
}
catch (Exception ex) {
Log.i("zdd", ex.getLocalizedMessage());
}
holder.imageView.setImageBitmap(bitmap);
//holder.image.setImageResource(imagesArray.get(position));
return row;
}
static class ViewHolder {
ImageView imageView;
}
}
SquareImageView
public class SquareImageView extends ImageView
{
public SquareImageView(Context context)
{
super(context);
}
public SquareImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
Here is the layout
activity_gridview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#7f7f7f"
android:numColumns="4"
android:horizontalSpacing="2dp"
android:verticalSpacing="2dp"
android:gravity="center"
android:stretchMode="columnWidth"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</GridView>
</RelativeLayout>
row_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#ffffff">
<com.jiyuzhai.setimagebitmaptest.SquareImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</LinearLayout>
Try changing the row item's parent size to "match_parent".
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
android:background="#ffffff">
<com.jiyuzhai.setimagebitmaptest.SquareImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</LinearLayout>
Try removing "padding" property from linear layout (or setting it to 0dp) and setting scaleType to fitXY in SquareImageView.
Related
I have a grid of images that were taken from a custom camera activity.
On other activity I load the images into a grid.
I have a method that turn on & off a checkbox on each Image.
While trying to move through all the images, I'm getting some strange behavior:
GridView.getCount() returns the correct number of images in the GridView, but GridView.getChildAt() method returned only part of the images.
so, when I try to do so, I get a null Exception.
The GridView Adapter:
public class PhotoGalleryAdapter extends ArrayAdapter {
// Declare variables
private Activity adapterActivity;
private int layoutResourceId;
private ArrayList gridItemsArray;
private static LayoutInflater inflater = null;
public PhotoGalleryAdapter(Activity a, int layoutResourceId, ArrayList fGridItemArray) {
super(a, layoutResourceId, fGridItemArray);
this.layoutResourceId = layoutResourceId;
this.adapterActivity = a;
this.gridItemsArray = fGridItemArray;
}
public int getCount() {
return gridItemsArray.size();
}
public Object getItem(int position) {
return gridItemsArray.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
HolderViewRow holderRow = null;
View rowView = (View) convertView;
if (rowView == null){
LayoutInflater inflater = adapterActivity.getLayoutInflater();
rowView = inflater.inflate(layoutResourceId, parent, false);
holderRow = new HolderViewRow();
holderRow.imageFileBMP = (ImageView) rowView.findViewById(R.id.imageObject);
holderRow.checkBox = (CheckBox) rowView.findViewById(R.id.itemCheckBox);
holderRow.checkBoxImage = (ImageView) rowView.findViewById(R.id.itemImageCheckBox);
rowView.setTag(holderRow);
}
else
{
holderRow = (HolderViewRow) rowView.getTag();
}
PhotoGalleryItem item = (PhotoGalleryItem) gridItemsArray.get(position);
// Set the decoded bitmap iitemnto ImageView
holderRow.imageFileBMP.setImageBitmap(item.getImageBMP());
holderRow.imageFilePath = item.getImagePath();
return rowView;
}
static class HolderViewRow {
ImageView imageFileBMP;
String imageFilePath;
CheckBox checkBox;
ImageView checkBoxImage;
}
}
public class PhotoGalleryItem {
private Bitmap imageBMP;
private String imagePath;
private CheckBox checkBox;
private ImageView checkBoxImage;
public PhotoGalleryItem(Bitmap imageBMP, String imagePath) {
super();
this.imageBMP = imageBMP;
this.imagePath = imagePath;
}
public Bitmap getImageBMP() {
return imageBMP;
}
public void setImageBMP(Bitmap imageBMP) {
this.imageBMP = imageBMP;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
The Grid Activity:
private void RenderGridAndSetImages() {
// Locate the GridView in gridView_PhotoDisplay.xml
gridView = (GridView) findViewById(R.id.gridView_PhotoDisplay);
// Pass String arrays to Adapter Class
imageAdapter = new PhotoGalleryAdapter(this, R.layout.gridview_photo_item, GridItemArrayList);
gridView.setAdapter(imageAdapter);
}
And the function that has the problem:
public void SetVisibilityCheckBox_OnGrid (boolean checkBoxVisibility) {
// Handle item selection On GRIDVIEW ImageItem
final int size = gridView.getCount();
try {
ImageView imageCB;
int cbVisibility;
if (checkBoxVisibility)
cbVisibility = View.VISIBLE;
else
cbVisibility = View.INVISIBLE;
for(int i = 0; i < size; i++) {
View viewItem = (View) gridView.getChildAt(i);
if (viewItem != null) {
imageCB = (ImageView) viewItem.findViewById(R.id.itemImageCheckBox);
imageCB.setVisibility(cbVisibility);
}
}
}
catch (Exception ex) {
// Error occurred while SetSelectCheckBoxOnGrid
Log.e(PACKAGE_NAME, ACTIVITY_NAME + ".SetVisibilityCheckBox_OnGrid\n" + ex.getMessage());
}
}
The GridView Layout:
<RelativeLayout
android:id="#+id/layout_Holder"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#color/activityBackground"
tools:context="com.mountain.saymera.PhotoGalleryActivity">
<!-- Image view: layout_GridView -->
<RelativeLayout
android:id="#+id/layout_PhotoGridDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:background="#color/activityBackground"
android:padding="1dp">
<GridView
android:id="#+id/gridView_PhotoDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:numColumns="auto_fit"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:focusable="true"
android:clickable="true"/>
<TextView
android:id="#+id/textView_NoImages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gallery_no_images"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#00000000"
android:textColor="#color/MenuButtonTint"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
The GridView Item Layout:
<RelativeLayout
android:id="#+id/layout_Holder"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/single_photo_frame_on_grid">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:background="#color/Grid_ItemFrame"
android:padding="0.3dp">
<com.mountain.saymera.SquareImageView
android:id="#+id/imageObject"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
</LinearLayout>
<CheckBox
android:id="#+id/itemCheckBox"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="invisible"
android:tint="#color/Grid_ItemCheckbox"/>
<ImageView
android:id="#+id/itemImageCheckBox"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="invisible"
android:background="#00000000"
android:src="#mipmap/ic_crop_square_black_24dp"
android:tint="#color/MenuCheckboxTint"/>
</RelativeLayout>
Need some help, Thanks
I have faced the same issue with programatically added ImageViews in a LinearLayout. Unfortunately, this method seems to be buggy at the moment, so I had to help myself by finding an alternative.
As a workaround, I saved the references of my ImageViews in a List and worked with them.
GridView is scrolled programmatically, and no new item appears coming up from the bottom.
I tried to update with the following line, but it does not force GridView to load new items.
imageAdapter.notifyDataSetChanged();
gridview.invalidateViews();
gridview.setAdapter(imageAdapter);
Simplified the app, now the scrolling can be fired with button click, but the upcoming empty items are still appearing. Here is some code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGridView gridview = (CustomGridView) findViewById(R.id.gridView1);
final ImageAdapter imageAdapter = new ImageAdapter(this);
gridview.setAdapter(imageAdapter);
gridview.setNumColumns(3);
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)gridview.getLayoutParams();
linearParams.width=66*3;
gridview.setLayoutParams(linearParams);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gridview.scrollBy(0, 44);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return 300;
}
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(66, 66));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0); // 8 8 8 8
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(R.drawable.asdf);
return imageView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.j4nos.moviebuffs12.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView"
android:layout_width="198dp"
android:layout_height="match_parent"
android:layout_marginTop="66dp"
android:layout_marginLeft="0dp"
android:layout_marginBottom="0dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<com.j4nos.moviebuffs12.CustomGridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:columnWidth="66dp"
android:horizontalSpacing="0dp"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="horizontal"
android:stretchMode="none"
android:verticalSpacing="0dp"
android:listSelector="#null"
android:scaleType="centerCrop">
</com.j4nos.moviebuffs12.CustomGridView>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
public class CustomGridView extends GridView {
public CustomGridView(Context context) {
super(context);
}
public CustomGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/* ADD THIS */
#Override
public int computeVerticalScrollOffset() {
return super.computeVerticalScrollOffset();
}
}
I think the problem is with the way you are scrolling:
gridview.scrollBy(0, 44);
This moves the gridview, not the content of the gridview. You can verify this by adding the following into your layout inside the CustomGridView component:
android:fastScrollAlwaysVisible="true"
Now you can see it's not the gridview content that is being interacted with on the button press.
Instead, I suggest you try to use:
gridview.scrollListBy(44);
if your API level allows it.
I make WearableListView list. Problem is that setting android:layout_height="20dp" doesn't help
How to set height in this case? In Android Wear sample projects Notifications and Timer they also just set atribute android:layout_height="80dp". But I tried to set in the projects android:layout_height="20dp" but it didn't help! (below is my project source code):
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<base.mobitee.com.mobiteewatch.adapter.HolesListItemLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="20dp"
android:gravity="center_vertical" >
<TextView
android:id="#+id/text_hole"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:textSize="#dimen/list_item_text_size" />
</base.mobitee.com.mobiteewatch.adapter.HolesListItemLayout>
HolesListItemLayout.java:
public class HolesListItemLayout extends LinearLayout
implements WearableListView.OnCenterProximityListener {
private TextView mName;
private final int mFadedTextColor;
private final int mChosenTextColor;
public HolesListItemLayout(Context context) {
this(context, null);
}
public HolesListItemLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HolesListItemLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
mFadedTextColor = getResources().getColor(R.color.grey);
mChosenTextColor = getResources().getColor(R.color.black);
}
// Get references to the icon and text in the item layout definition
#Override
protected void onFinishInflate() {
super.onFinishInflate();
mName = (TextView) findViewById(R.id.text_hole);
}
#Override
public void onCenterPosition(boolean animate) {
mName.setTextSize(18);
mName.setTextColor(mChosenTextColor);
}
#Override
public void onNonCenterPosition(boolean animate) {
mName.setTextColor(mFadedTextColor);
mName.setTextSize(14);
}
}
HolesListAdapter.java:
public class HolesListAdapter extends WearableListView.Adapter {
private final Context mContext;
private final LayoutInflater mInflater;
public HolesListAdapter(Context context) {
this.mContext = context;
mInflater = LayoutInflater.from(context);
}
#Override
public WearableListView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new WearableListView.ViewHolder(
mInflater.inflate(R.layout.list_item_hole, null));
}
#Override
public void onBindViewHolder(WearableListView.ViewHolder holder, int position) {
TextView text = (TextView) holder.itemView.findViewById(R.id.text_hole);
text.setText(mContext.getString(R.string.hole_list_item) + " " + (position + 1));
text.setTextColor(mContext.getResources().getColor(android.R.color.black));
holder.itemView.setTag(position);
}
#Override
public int getItemCount() {
return Preferences.HOLES;
}
}
The WearableListView is hard-coded to only display three items at a time - it measures the item height by dividing the list view's height by three ... so there isn't a practical way of doing what you want.
I suggest making the text font larger ...
I've got idea. Insert list into FrameLayout container. And by changing height of container list item height is changed. Result:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_centerInParent="true">
<android.support.wearable.view.WearableListView
android:id="#+id/wearable_list_game_options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dividerHeight="0dp"
android:scrollbars="none"/>
</FrameLayout>
</RelativeLayout>
Add one LinearLayout inside and set
android:layout_height="50dp"
android:layout_margin="5dp"
I have a image Gallery, and i want to show the last modified data below each image, but nothing is shown in the TextView (but yes in the ImageView). This is my adapter.
public class ImageAdapter extends BaseAdapter implements SpinnerAdapter {
private Context context;
private Drawable[] pics;
private String[] filePaths;
public ImageAdapter(Context context, Drawable[] pics, String[] filePaths) {
this.context=context;
this.pics =pics;
this.filePaths=filePaths;
}
#Override
public int getCount() {
return pics.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v=view;
ImageView imageView;
TextView textView;
if(v==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.gallery_item, null);
}
imageView=(ImageView)v.findViewById(R.id.galleryImageView);
textView=(TextView)v.findViewById(R.id.galleryTextView);
imageView.setLayoutParams(new Gallery.LayoutParams(115, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
File f=new File(filePaths[i]);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd/MM/yyyy");
Date lastModified=new Date(f.lastModified());
imageView.setImageDrawable(pics[i]);
textView.setText(simpleDateFormat.format(lastModified));
return imageView;
}
}
And this is my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/galleryImageView" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/galleryTextView"
android:textColor="#000"/>
</LinearLayout>
As I said, the image is shown, but there is no text below it.
You are returning ImageView instead of View(Layout).
Use this code
return v;
Return
return v;
instead of
return imageView;
Here i practice some tutorial of making gridview with auto resize image. i'm adopted this tutorial to my activity. what i'm gonna do next is how to make the image clickable. so that when users clicked on each image it goes to some class/activity.
Here is several code from the program I experimented :
activity_main.xml to throw a gridview into layout,stretch mode and column width :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:numColumns="2"
/>
</FrameLayout>
MainActivity.java custom ImageView that maintains its aspect ratio:
public class MainActivity extends ImageView {
public MainActivity(Context context) {
super(context);
}
public MainActivity(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MainActivity(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
This is a layout for a grid item :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.conversa.MainActivity
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="#android:color/white"
android:background="#55000000"
/>
</FrameLayout>
This is an adapter for gridview :
public class MyAdapter extends BaseAdapter {
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
items.add(new Item("Conversation 1", R.drawable.pic1));
items.add(new Item("Conversation 2", R.drawable.pic2));
items.add(new Item("Conversation 3", R.drawable.pic3));
items.add(new Item("Conversation 4", R.drawable.pic4));
items.add(new Item("Conversation 5", R.drawable.pic5));
items.add(new Item("Conversation 6", R.drawable.pic6));
items.add(new Item("Conversation 7", R.drawable.pic7));
items.add(new Item("Conversation 8", R.drawable.pic8));
items.add(new Item("Conversation 9", R.drawable.pic9));
items.add(new Item("Conversation 10", R.drawable.pic10));
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).drawableId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.gridimage, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private class Item {
final String name;
final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
And this is where the adapter set into gridview :
public class Gridpiw extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}
}
What should I add or maybe modify so that the image can be clicked to show new activity?
You should do it like this:
Firstly, create you activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Secondly, change your Gridpiw to MainActivity classname:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}
}
Thirdly, change your MainActivity extends ImageView to MeasuredImageView extends ImageView, like this:
public class MeasuredImageView extends ImageView {
public MeasuredImageView(Context context) {
super(context);
}
public MeasuredImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MeasuredImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
Then, include it into your grid item layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.conversa.MeasuredImageView
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:scaleType="centerCrop"
/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="#android:color/white"
android:background="#55000000"
/>
</FrameLayout>
NOTE: your ImageView with id "picture" should have attribute android:clickable="true".
Then in your adapter you should store the context, passed as the parameter.
public class MyAdapter extends BaseAdapter {
...
private Context context
...
public MyAdapter(Context context) {
this.context = context;
//your actions...
}
}
And finally, in your getView() function of the adapter class, you should setOnClickListener to your ImageView:
...
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.gridimage, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SecondActivity.class);
context.startActivity(intent);
}
});
return v;
}
...
Hope this helps.
Add This Kind Of Code For ImageViews to Your Code Inside Your Adapter Inside getView()
Add onClickListener()
picture.setOnClickListener(new OnClickListener() {
// Start new list activity
public void onClick(View v) {
Intent mainIntent = new Inten(SampleMainActivity.this,SecondActivity.class);
startActivity(mainIntent);
}
}