How communicate between Adapter and Activity - android

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.

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.

Touch to image view not working

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);
}
});

Image slider using View Pager issue

I have an activity which contains a listView. Each item of the listView contains a swipeable set of images (which I have unsuccessfully tried to implement using a ViewPager).
My issue is this: when I try to implement a simple image slider using a view pager (i.e. Activity contains a ViewPager, and the View Pager's adapter supplies the images), the output is as expected, but if I try doing what I have mentioned in the previous paragraph (i.e. The Activity contains a listView and each item of the listView is a ViewPager which displays a swipeable set of images), I get a blank output. Please help me out! I have posted some code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.stylistDisplay);
//To keep things simple I am sending only one item of the list to the adapter
list.setAdapter(new StylistAdapter(Cart.getList().get(0), this));
}
static class StylistAdapter extends BaseAdapter {
Stylist stylistObj;
Context context;
LayoutInflater inflater;
public StylistAdapter(Stylist obj, Context context) {
this.stylistObj = obj;
this.context = context;
inflater = ((Activity)this.context).getLayoutInflater();
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return stylistObj;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = inflater.inflate(R.layout.stylist_photos_view_pager, null);
item = new ViewItem();
item.photosViewPager = (ViewPager) convertView.findViewById(R.id.photos_view_pager);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
PhotosAdapter adapter = new PhotosAdapter(context);
item.photosViewPager.setAdapter(adapter);
return convertView;
}
private class ViewItem {
ViewPager photosViewPager;
}
}
activity_main.xml
<FrameLayout 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"
tools:context="com.temp.customer.MainActivity">
<ListView
android:id="#+id/stylistDisplay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:background="#color/backGround"
android:padding="13.3dp"
android:clickable="true"
android:dividerHeight="5dp" />
</FrameLayout>
stylist_photos_view_pager
<RelativeLayout xmlns:android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/photos_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
PhotosAdapter.java
public class PhotosAdapter extends PagerAdapter {
private Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
public PhotosAdapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.stylist_individual_details, container, false);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.iv1);
imageView.setImageResource(GalImages[position]);
TextView textView1 = (TextView) viewItem.findViewById(R.id.tv1);
textView1.setText("hello world");
((ViewPager)container).addView(viewItem);
return viewItem;
}
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(View view, Object object) {
boolean temp = view == ((LinearLayout) object);
return temp;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((LinearLayout) object);
}
}
I've experienced similar issue, and have to say that it is a bad idea to use ViewPager as a listItem, since ViewPager is supposed to be used for fragments primarily.
I guess that your functionality should be similar to some horizontal pictures, on the main feed which is vertical. You can think of using horizontal scroll views which is a bit of a pain, but still more realistic to do that. You might also end up managing your own scrolling behavior, which might already be implemented by some libraries.
BUT I MIGHT BE WRONG!
This thread has a similar issue:
Placing ViewPager as a row in ListView
After reading around for a while I tried explicitly setting the height of the viewPager and its parent. This worked for me.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="200dip"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="200dip" >
</android.support.v4.view.ViewPager>
</LinearLayout>
I don't know if there is a better solution, but if you do get a better solution please comment!

Custom ListView with button

I using custom adapter for displaying a list of items in my project,
Right now it is working fine.but now i got another requirement that i need to put a button on each item.
If put the button like that then the onItemClickListenter() for that item is not working ,instead onClickListener() for that button is working.
But according to my context both onClickListenter() for button and onItemClickListener() for that item should work.Can somebody please help me if know the technique.
Thanks in advance.
As Button is a focusable view thats why onItemClick isn't work. In ur_row.xml (where you placed that Button) add these attributes inside Button tag
android:focusable="false"
android:focusableInTouchMode="false"
Inside your CustomAdapter's getView(...) set onClickListener for that Button this will fire both onItemClick for ListView and onClick for Button.
You need a custom adapter:
This project contains 4 parts:
1.MainActivity
public class MainActivity extends Activity {
private ListView listView;
private CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
init();
}
/**
* Init Data
*/
public void init(){
List<String> listItems = new ArrayList<String>();
for(int i=0;i<10;i++) {
listItems.add("Test" + i);
}
listView = (ListView)findViewById(R.id.listView);
customAdapter = new CustomAdapter(MainActivity.this,R.layout.row_item,listItems);
listView.setAdapter(customAdapter);
}
}
2.MainActivity layout
<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"
tools:context=".main_activity">
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
3.CustomAdapter
public class CustomAdapter extends ArrayAdapter<String> {
private Context context;
private TextView itemListText;
private Button itemButton;
private List<String> listValues;
public CustomAdapter(Context context, int resource, List<String> listValues) {
super(context, resource,listValues);
this.context = context;
this.listValues = listValues;
}
/**
* getView method is called for each item of ListView
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String currentValue = listValues.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_item, null);
itemListText = (TextView)convertView.findViewById(R.id.itemListText);
itemListText.setText(currentValue);
itemListText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"Text Working",Toast.LENGTH_SHORT).show();
}
});
itemButton = (Button)convertView.findViewById(R.id.itemButton);
//To lazy to implement interface
itemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"Button Working",Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
4.Row Item layout
<?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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/itemListText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Select Text"
android:gravity="center_vertical"
android:layout_weight="0.7"/>
<Button
android:id="#+id/itemButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Push me"
/>
</LinearLayout>
Output:
TextView touch action
Button touch action
rather than putting buttons on row use image views as many required and set on click listener to them, Since imageViews are not focusable

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