Touch to image view not working - android

I've made a simple app in which I am using 3 tabs. Each tab is having separate classes and layouts. First tab shows map. Second tab will show the camera from which the user can take picture(s) and third tab is off Pictures in which the captured images are viewed in the GridView. All tabs are working good. Now I want is to show full ImageView when a user tap on any image.
For all of this I am using this tutorial. So I followed each and every step in it and the things are going good. But for full ImageView the code is not working.
Below is my picture Fragment
Pictures.java
public class Pictures extends Fragment implements MainActivity.Updateable {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.pictures, container, false);
gridView = (GridView) rootView.findViewById(R.id.grid_view);
utils = new Utils(getContext());
// Initilizing Grid View
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(getActivity(), imagePaths, columnWidth);
/*adapter = new GridViewImageAdapter(Pictures.this, imagePaths,
columnWidth);*/
// setting grid view adapter
gridView.setAdapter(adapter);
//((BaseAdapter) adapter).notifyDataSetChanged();
//adapter.notifyDataSetChanged();
return rootView;
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
#Override
public void update() {
if(adapter !=null)
{
adapter.notifyDataSetChanged();
}
else
{
Log.d(getTag(),"null");
}
}}
Now for full screen view, I have made a new Activity a two separate Layouts one for screen and one for image as below
fullscreen.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" /></LinearLayout>
fullscreenImage.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="#+id/imgDisplay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter" />
<Button
android:id="#+id/btnClose"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:background="#drawable/button_background"
android:textColor="#ffffff"
android:text="Close" /></RelativeLayout>
Now i created a Adapter class
FullScreenImageAdapter.java
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_activity.finish();
}
});
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}}
Now the full screen Activity
FullScreenViewActivity.java
public class FullScreenViewActivity extends Activity {
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager)findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position",0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
utils.getFilePaths());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}}
Now when i click on any image nothing happens, I got no errors on logcat, no any warnings nor any app crash.
I have debugged the app but it doesn't goes to that point.
I'm stuck to it, and don't know what to do
Any help would be highly appreciated.

This might not be the answer that you are looking for! But still if your code does not work this will help you towards your solution.If you know the whole process you might be able to plug and play this.
This answer is taken from the same tutorial guy that you followed which has kind of a same pattern with your code. Note image array is hard-coded.
Have a look, Take a special note at AndroidGridLayoutActivity !
Launcher Activity : HomeActivity Other activity you need in your Manifest :FullImageActivity
grid_layout.xml >
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:fitsSystemWindows="true"
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:gravity="center">
</GridView>
full_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" >
<ImageView android:id="#+id/full_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout
HomeActivity >
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
}
AndroidGridLayoutActivity > (check the comments in this)
public class AndroidGridLayoutActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//----------------------Seems In your code you are missing this Part----------------------
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
}
ImageAdapter >
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array - I have hard coded this
public Integer[] mThumbIds = {
R.drawable.casper, R.drawable.casper,
R.drawable.monkey, R.drawable.monkey,
R.drawable.cub, R.drawable.cub,
R.drawable.mouse, R.drawable.mouse,
R.drawable.casper, R.drawable.casper,
R.drawable.monkey, R.drawable.monkey,
R.drawable.cub, R.drawable.cub,
R.drawable.mouse
};
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150)); /// IF YOU WANT TO CHANGE IMAGE SIZE CHANGE HERE
return imageView;
}
}
As a separate project this will work.In case if you cant fix your issue plug and play this.Just posting as a help!
Output >

You can try using OnItemClickListener on your grid view like below
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Get your item here
adapterView.getItemAtPosition(i);
//Do your code here
}
});
Please make sure that you removed your click listener from getView otherwise it will make conflict.

Please make sure you have to intent single imageview class
Send position id to imageview class I used below code for full screen image view
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, Singleimageview.class);
i.putExtra("pos", (Integer) itemView.getTag() + "");
mContext.startActivity(i);
overridePendingTransition(R.anim.pull_in_left, R.anim.pull_out_right);
}
});

Related

Loading images from the custom video gallery

I'm working on a page in which I have a button which takes you to the video gallery which I have created. From this you select some videos(thumbnails) and then hit the arrow to come back to the same place from where I hit the button to come to the Custom gallery with the selected videos.
Basically the map goes like this :
Button(from AddFragment)->VideoGallery->Select videos-> AddFragment with selected videos which is visible inside the recycler view
Now when I hit the button I come to my videogallery but when I select some videos from the gallery and come back to the AddFragment it shows nothing and one error comes up that is E/RecyclerView: No adapter attached; skipping layout
Now I have used Bundle to extract the sent data and populate it in my AddFragment.
I'm giving out the code for you :
1. AddFragment.java
public class AddFragment extends Fragment {
private ImageButton nextActivity;
private RecyclerView recyclerView;
private ProgressDialog videoProgressDialog;
ArrayList<File> checkedList = new ArrayList<>();
ImageAdapter imageAdapter;
Button button;
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
nextActivity = (ImageButton) view.findViewById(R.id.gotoButton);
recyclerView = (RecyclerView) view.findViewById(R.id.grid_add_view);
button = (Button) view.findViewById(R.id.buttonToGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(),VideoGalleryActivity.class));
}
});
return view;
}
//making adapter for RecyclerView which loads the desired files
class ImageAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mInflater;
private Bitmap bitmap;
private ArrayList<File> fileName;
public ImageAdapter(ArrayList<File> checkedList) {
fileName = checkedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue){
File filePath = new File(pathName);
checkedList.add(filePath);
}
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
View items = mInflater.from(parent.getContext()).inflate(R.layout.custom_added_video,
parent,false);
items.setLayoutParams(new AbsListView.LayoutParams(215,215));
return new ViewHolder(items);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(fileName != null){
bitmap = ThumbnailUtils.createVideoThumbnail(fileName.get(position).toString(),1);
holder.imageView.setImageBitmap(bitmap);
}
}
#Override
public int getItemCount() {
return fileName.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
//public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
//imageButton = (ImageButton) itemView.findViewById(R.id.addVideos);
imageView = (ImageView) itemView.findViewById(R.id.galleryImageView);
}
} }
2. fragment_add.xml
<LinearLayout 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:orientation="vertical"
android:background="#color/colorWhite"
tools:context="in.pinelane.myhovi.AddFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linearLayout"
android:padding="19dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textStyle="bold"
android:text="Choose Videos"
android:textColor="#color/colorBackground"/>
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<ImageButton
android:id="#+id/gotoButton"
android:layout_width="25sp"
android:layout_height="25sp"
android:background="#00ffffff"
android:src="#mipmap/ic_arrow_forward_black_24dp"/>
</LinearLayout>
<Button
android:id="#+id/buttonToGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/grid_add_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
Inflates this layout
custom_added_video.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_marginEnd="3dp"
android:layout_marginStart="3dp">
<!--<ImageButton-->
<!--android:id="#+id/addVideos"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:src="#mipmap/ic_add_black_24dp"-->
<!--android:layout_margin="3dp"-->
<!--android:background="#drawable/edittext_border"-->
<!--android:layout_centerInParent="true"/>-->
<ImageView
android:id="#+id/galleryImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_margin="3dp"
android:layout_centerInParent="true"/>
Any idea would be of great help! Thanks
I've tried defining the below code in onCreate but I got a NullPointerException so I defined the same inside the onCreateViewHolder but no result just No Adapter attached; skipping layout
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue){
File filePath = new File(pathName);
checkedList.add(filePath);
}
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
EDITS
I've made some changes inside my code and user onActivityResult and startActivityForResult in this fragment but still no result. My AddFragment is still blank and not showing any result
Edited AddFragment.java
public class AddFragment extends Fragment {
private ImageButton nextActivity;
private RecyclerView recyclerView;
ArrayList<File> checkedList = new ArrayList<>();
ImageAdapter imageAdapter;
Button button;
private static final int CustomGallerySelectId = 1;//Set Intent Id
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
nextActivity = (ImageButton) view.findViewById(R.id.gotoButton);
recyclerView = (RecyclerView) view.findViewById(R.id.grid_add_view);
button = (Button) view.findViewById(R.id.buttonToGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(getContext(),VideoGalleryActivity.class),CustomGallerySelectId);
}
});
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
GridLayoutManager videoGrid = new GridLayoutManager(getContext(),3);
recyclerView.setLayoutManager(videoGrid);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case CustomGallerySelectId :
if(requestCode == RESULT_OK){
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue) {
File filePath = new File(pathName);
checkedList.add(filePath);
}
}
}
}
//making adapter for RecyclerView which loads the desired files
class ImageAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mInflater;
private Bitmap bitmap;
private ArrayList<File> fileName;
public ImageAdapter(ArrayList<File> checkedList) {
fileName = checkedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View items = mInflater.from(parent.getContext()).inflate(R.layout.custom_added_video,
parent,false);
items.setLayoutParams(new AbsListView.LayoutParams(215,215));
return new ViewHolder(items);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(fileName != null){
bitmap = ThumbnailUtils.createVideoThumbnail(fileName.get(position).toString(),1);
holder.imageView.setImageBitmap(bitmap);
}
}
#Override
public int getItemCount() {
return fileName.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
//public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
//imageButton = (ImageButton) itemView.findViewById(R.id.addVideos);
imageView = (ImageView) itemView.findViewById(R.id.galleryImageView);
}
} }
Move this code:
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
to your createView() method.
In createView you are inflating the layout, you are finding the RecyclerView but you are not setting an adapter to it. The RecyclerView doesn't have any data to show, so it's skipped from the layout for a performance boost. You should also set a LayoutManager. If you need a simple list, you should use LinearLayoutManager.
The createViewHolder() method is called once for each visible element of your RecyclerView. It's not the right place to perform the initial setup of your RecyclerView.

How to create Transparence Thumbnail Gallery?

hy there, i will create Android Gallery on my app, but this not perfect because use old Interface, i hope my Gallery look modern UI, can you help, my Gallery look like this :
i want my gallery look like this :)
this is my code :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#null"
>
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#null"
/>
<ImageView
android:id="#+id/image1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="matrix"
android:background="#null"/>
</LinearLayout>
and my Activity:
public class MainActivity extends Activity {
//---raw---
Integer[] imageID = {
R.drawable.gbr1,
R.drawable.gbr2,
R.drawable.gbr3,
R.drawable.gbr4
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(getBaseContext(), "Foto" + (position + 1) + " dipilih", Toast.LENGTH_SHORT).show();
//---show click img---
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageID[position]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c) {
context = c;
//---style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
a.recycle();
}
//--- back mount picture---
public int getCount() {
return imageID.length;
}
//---back ID item---
public Object getItem(int position) {
return position;
}
//---back ID item---
public long getItemId(int position) {
return position;
}
//---back view ImageView---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageID[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
thanks for All before :D
You can use traditional components that are exist in the Github (github.com) for this purpose.
Or design it by yourself (that's more flexible way!)
But it may need to write couple of custom controls to achieve the appearance you want.
Both pictures you attached, almost have the same core (Code Behind) and the main difference between them is their design.

getView() method displays only one ImageButton in the GridView

I am trying to use the GridView to create a set of Image buttons.
I am using an array list to store the images. Every time an image is assigned to a button through the getView() method, the images array list is reduced by one.
my problem is that only one button is shown in my grid! I am not sure if this is because the getView() method is called more than one time for each button. If so, I guess the array of images becomes empty before all buttons are assigned.
Any help is appreciated.
here is my code
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView1"
android:layout_width= 'fill_parent'
android:layout_height= 'fill_parent'
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
item_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="35dp"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
Images as assigned randomly to the buttons and then removed from the list:
the assignImag()e method is in the MainActivity class and is called every time from the getView() method of the adapter class:
public class MainActivity extends Activity {
ArrayList imgs = new ArrayList();
GridView gridView;
.....
......
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ButtonAdapter(this));
}
public class ButtonAdapter extends BaseAdapter
{
private Context context;
ImageButton imageButton;
public ButtonAdapter(Context c)
{
context = c;
}
//---returns the number of images---
public int getCount() {
return imgs.size();
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.item_layout, null);
imageButton = (ImageButton) gridView.findViewById(R.id.button1);
// assign image to the button
assignImage(imageButton);
} else {
gridView = (View) convertView;
}
return gridView;
}
}
}
public void assignImage(ImageButton b){
Random generator = new Random();
int index = generator.nextInt(imgs.size());
b.setContentDescription(imgs.get(index).toString());
b.setBackgroundResource(imgs.get(index));
imgs.remove(index);
}
}
Modify your adapter like this:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
-----
R.drawable.imgN
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(67, 55));
return imageView;
}
}
No need to create separate layout for each image in the gridView

How communicate between Adapter and Activity

I'm not sure what's the best way to communicate from an Adapter to the corresponding Activity.
My activity has a layout with a WebView and a Gallery on top of it:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical" >
<Gallery
android:id="#+id/gallery"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
android:spacing="2dip" />
<WebView
android:id="#+id/webview"
android:layout_height="wrap_content"
android:layout_weight="5"
android:layout_width="fill_parent" />
</LinearLayout>
The activity loads image data into the Gallery:
public class MyActivity extends Activity {
private MyAdapter adapter;
private Container container;
private ArrayList<Container> containers = new ArrayList<Container>();
private Gallery gallery;
private WebView webView;
#Override
public void onCreate(Bundle bundle) {
...
gallery = (Gallery) findViewById(R.id.gallery);
webView = (WebView) findViewById(R.id.webview);
containers = fetchContainers();
doGallery();
}
private void doGallery() {
adapter = new MyAdapter(this,
containers);
gallery.setAdapter(adapter);
}
private ArrayList<Container> fetchContainers() {
ArrayList<Container> containers = null;
...
return containers;
}
}
A click on one of these images should change the contents of the webview. Here's the adapter with the OnClickListener:
public class MyAdapter extends BaseAdapter {
private class MyOnClickListener implements OnClickListener {
private Container container;
private Context context;
public MyOnClickListener(Context context, Container container) {
this.container = container;
this.context = context;
}
public void onClick(View view) {
//TODO: change contents of WebView
}
}
private ArrayList<Container> containers;
private Context context;
public View getView(final int position, final View contentView, final ViewGroup viewGroup) {
ImageView imageView = new ImageView(context);
Container container = containers.get(position);
// get image data from image cache
imageView.setOnClickListener(new MyOnClickListener(context, container));
return imageView;
}
public MyAdapter(Context context, ArrayList<Container> containers) {
this.containers = containers;
this.context = context;
}
}
Now my question is. How do I notify the activity about what image has been clicked on and transfer one object to the activity?
My thoughts are to use a BroadcastReceiver but I don't think that this is the prefered way to do so. What should I do?
Many thanks in advance.
Instead creating Imageview's click listener, use gallery's setOnItemClickListener
yourGallery.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) {
system.out.println("position"+position);
}
});
Use the setOnItemClickListener method of your Gallery object in the activity.

Horizontal scrolling in android gridview

I have a grid view in my application and i need to scroll it horizontally.I have tried changing the gridview to gallery.But then only one row is available,but i need different rows as in a grid view.So basically what i need is a gridview that can be scrolled horizontally.Is there any efficient way to do this?Thanks in advance.
Regards
Anu
Hi,Thanks for the reply.i have tried using a Gallery and implement an adapter that provides a multirow view in its getView method.
My java file is:
public class Gridview extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new GridAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(Gridview.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
public class GridAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
};
public GridAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if(convertView==null)
{
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
iv.setImageResource(R.drawable.icon);
}
else
{
v = convertView;
}
return v;
}
}
}
main.xml is :
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
icon.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/icon_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</ImageView>
</LinearLayout>
The output i got is : http://www.4shared.com/photo/MzUcmzel/device.html
But this is not i need actually.i want the icons in different rows.Any help is appreciated.
I think your best bet is to use a Gallery and implement an adapter that provides a multirow view in its getView method. See Hello Gallery and look at the ImageAdapter implementation within.
Instead of the ImageView that getView returns in that example, you can, for example, inflate your own custom layout, for example a LinearLayout with vertical orientation.
You might consider a TableLayout inside a HorizontalScrollView, but the disadvantage there is that everything will be in memory at once, making it difficult to scale to lots of items. The Gallery recycles Views and offers some resource advantages.
I have already posted this answer here and here, but these questions are
identical...
There is a nice solution in Android from now on : HorizontalGridView.
1. Gradle dependency
dependencies {
compile 'com.android.support:leanback-v17:23.1.0'
}
2. Add it in your layout
your_activity.xml
<!-- your stuff before... -->
<android.support.v17.leanback.widget.HorizontalGridView
android:layout_width="wrap_content"
android:layout_height="80dp"
android:id="#+id/gridView"
/>
<!-- your stuff after... -->
3. Layout grid element
Create a layout for your grid element ( grid_element.xml ). I have created a simple one with only one button in it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button" />
</LinearLayout>
4. Create an adapter
Highly inspired by this link : https://gist.github.com/gabrielemariotti/4c189fb1124df4556058
public class GridElementAdapter extends RecyclerView.Adapter<GridElementAdapter.SimpleViewHolder>{
private Context context;
private List<String> elements;
public GridElementAdapter(Context context){
this.context = context;
this.elements = new ArrayList<String>();
// Fill dummy list
for(int i = 0; i < 40 ; i++){
this.elements.add(i, "Position : " + i);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final Button button;
public SimpleViewHolder(View view) {
super(view);
button = (Button) view.findViewById(R.id.button);
}
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(this.context).inflate(R.layout.grid_element, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.button.setText(elements.get(position));
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Position =" + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return this.elements.size();
}
}
5. Initialize it in your activity :
private HorizontalGridView horizontalGridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
horizontalGridView = (HorizontalGridView) findViewById(R.id.gridView);
GridElementAdapter adapter = new GridElementAdapter(this);
horizontalGridView.setAdapter(adapter);
}
True about using a Gallery or ListView re: re-using views. But if your list is not too long, you can try a TableLayout with a ViewFlipper. Here's a summary of possible options/solutions.
This post might get help you out what you wanted to achieve
Scroll like Shelf View
how about using a viewPager :
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
?
Try to wrap it in HorizontalScrollView

Categories

Resources