I have a list with userEntries. Each of these entries contains one block where I have some dynamic content, in this case a viewpager containing 1-3 images. My problem comes when I want to these images to have the correct Height. If I set my ViewPager height to for example 100dp the image is shown and the ViewPager works as expected. However if I rotate the phone or use a screen that is abit larger the image stays the same width as the 100dp is limiting it from getting the correct width. As this happends I want to use wrap_content so it resizes its height in order to fill the image to its full width, but when I do that the layout is minimized. See screens and code below.
CustomViewHolder.java <- This holds the userentry
public void populateContentArea(int mListType, Context context){
switch (mListType){
case Constants.ListType.DATE_LIST:
DatingEntryModel dateUser = (DatingEntryModel)mUser;
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View datingContent = layoutInflater.inflate(R.layout.dating_picture_container, llUserEntryContent, true);
ViewPager datingPager = (ViewPager) datingContent.findViewById(R.id.datingPager);
datingPager.setAdapter(new DatingPictureAdapter(context, dateUser.activities));
TabLayout datingIndicator = (TabLayout) datingContent.findViewById(R.id.datingTabDots);
datingIndicator.setupWithViewPager(datingPager);
break;
default:
break;
}
}
dating_picture_container.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/datingPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.design.widget.TabLayout
android:id="#+id/datingTabDots"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_width="70dp"
android:layout_height="20dp"
app:tabIndicatorHeight="0dp"
app:tabPaddingBottom="10dp"
app:tabBackground="#drawable/tab_dot_selector"
app:tabGravity="center"/>
</RelativeLayout>
DatingPictureAdapter.java
public class DatingPictureAdapter extends PagerAdapter {
private Context mContext;
List<DatingActivity> mActivities;
public DatingPictureAdapter(Context context, List<DatingActivity> activities) {
mContext = context;
mActivities = activities;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
DatingActivity activity = mActivities.get(position);
final ImageView datingBanner = new ImageView(mContext);
datingBanner.setAdjustViewBounds(true);
datingBanner.setScaleType(ImageView.ScaleType.FIT_CENTER);
UrlManager.loadDatingBannerGlide(mContext, activity.id).into(datingBanner);
collection.addView(datingBanner, 0);
return datingBanner;
}
#Override
public int getCount() {
return mActivities.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
}
At the end of the day, setting the height static to 10dp and then resize depending on the image width was the best solution for me. Thanks for all responses :)
I think it's because of you set your ViewPager's height "wrap_content" wrap_content does not work for ViewPager. If you change it to match_parent or to a static dp your issue'll be fixed.
<android.support.v4.view.ViewPager
android:id="#+id/datingPager"
android:layout_width="match_parent"
android:layout_height="144dp"/>
I think you have 2 ways to do that:
1- if you want to use differents layouts with different orientation you must create one layout for each orientation
2- you can get progammatically get the height of display and put inside layout dinamically proportional height
i hope this help you
I want to create below layout under which item will scroll vertically. whenever we scroll up or down the centered(28) textview should be zoom in position.i found this link Gallery like view with center image zoom but they scroll horizontally using image based on their requirement. i need vertically scroll only using textview
please let me know if any body know the logic.......
First of all, thanks to #sanjay kumar had a good question.
After 2 days, I found a best solution for this question.
You can use RecyclerView and make sure the LinearLayoutManager should like this
LinearLayoutManager yourLinearLayout= new LinearLayoutManager(getApplicationContext());
yourLinearLayout.setOrientation(LinearLayoutManager.VERTICAL);
yourLinearLayout.setLayoutManager(yearLayoutManager);
The most difficult problem is how can you get the middle Item of recyclerView, well I think you can learn more in this link:
https://github.com/plattysoft/SnappingList
Finally, to make the middle Item bigger than the others. In the RecyclerView's Adapter should be like this
public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
private ArrayList<LabelerDate> dateDataList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int selectedItem = -1;
public DateAdapter(ArrayList<Datasource> data, int paddingWidthDate) {
this.dateDataList = data;
this.paddingWidthDate = paddingWidthDate;
}
#Override
public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//todo
}
#Override
public void onBindViewHolder(DateViewHolder holder, int position) {
Datasource data = dateDataList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
holder.tvDate.setText(String.valueOf(data.valueDate));
holder.tvDate.setVisibility(View.VISIBLE);
holder.imgSmall.setVisibility(View.VISIBLE);
if (position == selectedItem) {
holder.tvDate.setTextColor(Color.parseColor("#094673"));
holder.tvDate.setTextSize(35);
holder.imgSmall.setBackgroundResource(R.color.textviewbold);
} else {
holder.tvDate.setTextColor(Color.GRAY);
holder.tvDate.setTextSize(35);
holder.imgSmall.setBackgroundResource(R.color.gray);
}
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
//todo
}
public class DateViewHolder extends RecyclerView.ViewHolder {
//todo
}}
After created The recyclerView, adapter and datasource. You can look at the onBindViewHolder(). If Item is selected then it's become bigger and change to black. If is not selected it will become Gray. My layout look like yours
use this library
Polidea view library
Put your TextView into a LinearLayout that lives on a ZoomView.
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.polidea.ZoomView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/myLinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</com.polidea.ZoomView>
</ScrollView>
The Polidea custom View didn't work in my case, as is. Had to a add a constructor with AttributeSet parameter, because it threw an xml inflation error. Also I had to make the ScrollView wrap only the TextView.
I have a linear layout which holds inner (child) custom image view.
My goal is to set a background selector on the image view, and also set a listener
to the linear layout.
however, I can't make the selector and the listener work together.
I don't know how to handle the events.
If I make a quick tap it is working, but If I drag my finger on the views, the image view
remains in selected state.
Here's the activity which has a reference to the linear layout and its listener.
public class EventDispatchingDemoActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.my_layout);
linearLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Click", Toast.LENGTH_SHORT).show();
}
});
}
}
Here's the custom view (Its a code I found somewhere, credits for the author)
public class ImageSelector extends ImageView
{
public ImageSelector(Context context, AttributeSet attrs)
{
super(context, attrs);
setBackgroundDrawable(new NavStateListDrawable(getContext(), 0));
setClickable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
super.onTouchEvent(event);
return false;
}
public class NavStateListDrawable extends StateListDrawable
{
private int level;
public NavStateListDrawable(Context context, int level)
{
this.level = level;
// int stateChecked = android.R.attr.state_checked;
int stateFocused = android.R.attr.state_focused;
int statePressed = android.R.attr.state_pressed;
int stateSelected = android.R.attr.state_selected;
addState(new int[] { stateSelected }, context.getResources().getDrawable(R.drawable.slide_feedback));
addState(new int[] { statePressed }, context.getResources().getDrawable(R.drawable.slide_feedback));
addState(new int[] { stateFocused }, context.getResources().getDrawable(R.drawable.slide_feedback));
addState(new int[] { -stateFocused, -statePressed, -stateSelected }, context.getResources().getDrawable(android.R.color.transparent));
}
#Override
protected boolean onStateChange(int[] stateSet)
{
boolean nowstate = super.onStateChange(stateSet);
try
{
LayerDrawable defaultDrawable = (LayerDrawable) this.getCurrent();
LevelListDrawable bar2 = (LevelListDrawable) defaultDrawable.findDrawableByLayerId(R.id.element_contact_image_selector);
bar2.setLevel(level);
}
catch (Exception exception)
{
}
return nowstate;
}
}
}
And Here's the xml:
<?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="fill_parent"
android:background="#acf1fa"
android:gravity="center"
android:orientation="vertical" >
<!-- outer layout -->
<LinearLayout
android:id="#+id/my_layout"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#00ff00"
android:gravity="center" >
<!-- inner layout -->
<dor.event.dispathing.ImageSelector
android:id="#+id/inner_layout"
android:layout_width="150dp"
android:layout_height="150dp" />
</LinearLayout>
</LinearLayout>
I Uploaded the source:
http://www.filefactory.com/file/5ikfwyk9j5bx/n/EventDispatchingDemo.rar
Thanks in advance for your help!
I remember having a similar issue when I was writing my application.
1) Are you trying to capture if a row in your listview is clicked? I think you want `listView.setonItemClickListener' which will capture clicks for each individual row as opposed to the entire listview.
2) I believe when you have a listview with clickable items inside it, the clickable items inside it take priority in terms of capturing clicks. More than taking priority, I believe they block any click events from being sent back to the parent's event handlers.
I believe a somewhat working solution is to set the focusability of those clickable items to false. Once those clickable items are not longer focusable, the listview row will get focus back. The other solution is to work with the descendantFocusability property which controls who (Entire row or Image) gets first crack and picking up events triggered within the row. Here are some other questions that seem to have what you need:
How to fire onListItemClick in Listactivity with buttons in list?
Android ListView with clickable items in it's rows causes problems continuing scrolling
I am reviewing and fixing some issues at an Android application that was developed from other developer.
He created a screen layout for normal screen size and inserted a GridView in it.
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="45dp"
android:horizontalSpacing="10dp"
android:columnWidth="120dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:layout_marginTop="30dp"
android:scrollbars="none"
/>
At code side images defined as integer array.
Integer[] a1 = { R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4, R.drawable.image5,R.drawable.image6,R.drawable.image6,R.drawable.image7,R.drawable.image8, R.drawable.image9,R.drawable.image10,R.drawable.image11
};
Integer array binded gridview with this code.
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageButtonAdapter(this,infox));
So here ise ImageButtonAdapter class
public class ImageButtonAdapter extends BaseAdapter {
private Context mContext;
public ImageButtonAdapter(Context c, Integer[] imageIds) {
mContext = c;
mThumbIds = imageIds;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageButton imageButtonx;
if (convertView == null) {
imageButtonx = new ImageButton(mContext);
imageButtonx.setBackgroundColor(Color.TRANSPARENT);
**imageButtonx.setLayoutParams(new GridView.LayoutParams(160, 160));**
imageButtonx.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageButtonx.setPadding(5, 5, 5, 5);
/* if ( position == 10 )
{
imageButtonx.setVisibility(ImageButton.GONE);
}
*/
} else {
imageButtonx = (ImageButton) convertView;
}
setMyTag(imageButtonx,mThumbIds[position]);
imageButtonx.setImageResource(mThumbIds[position]);
return imageButtonx;
}
private Integer[] mThumbIds;
}
Also, res\drawable-hdpi folder contains high resolution images that is 167x161 px and res\drawable-mdpi folder contains normal resolution images that is 82x72 px.
But at small screened devices, images streched. I think the bold code line cause this; but i couldn't fix it.
Do you have any suggestion how can i fix this problem and support large-normal and small screens?
LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
This is what i normally do, hope this will help.
yes due to this you are getting that problem
imageButtonx.setLayoutParams(new GridView.LayoutParams(160, 160))
change this code like this
imageButtonx.setLayoutParams(new GridView.LayoutParams(
(int) getResources().getDimension(R.dimen.width),
(int) getResources().getDimension(R.dimen.height)));
store width, height value in the values-->dimentions.xml folder like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="width">80dp</dimen> // your desired values
<dimen name="height">80dp</dimen>
</resources>
HTH..
Is it possible to make the ListView horizontally? I have done this using a gallery view, but the selected item comes to the center of the screen automatically. I don't want the selected item at the same spot I clicked. How can I rectify this problem? My idea was to set the ListView with a horizontal scroll. Share your idea?
As per Android Documentation RecyclerView is the new way to organize the items in listview and to be displayed horizontally
Advantages:
Since by using Recyclerview Adapter, ViewHolder pattern is
automatically implemented
Animation is easy to perform
Many more features
More Information about RecyclerView:
grokkingandroid.com
antonioleiva.com
Sample:
survivingwithandroid.com
Just add the below block to make the ListView to horizontal from vertical
Code-snippet
LinearLayoutManager layoutManager= new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(layoutManager);
Paul doesn't bother to fix bugs of his library or accept users fixes. That's why I am suggesting another library which has similar functionality:
https://github.com/sephiroth74/HorizontalVariableListView
Update: on Jul 24, 2013 author (sephiroth74) released completely rewritten version based on code of android 4.2.2 ListView. I must say that it doesn't have all the errors which previous version had and works great!
#Paul answer links to a great solution, but the code doesn't allow to use onClickListeners on items children (the callback functions are never called). I've been struggling for a while to find a solution and I've decided to post here what you need to modify in that code (in case somebody need it).
Instead of overriding dispatchTouchEvent override onTouchEvent. Use the same code of dispatchTouchEvent and delete the method (you can read the difference between the two here http://developer.android.com/guide/topics/ui/ui-events.html#EventHandlers )
#Override
public boolean onTouchEvent(MotionEvent event) {
boolean handled = mGesture.onTouchEvent(event);
return handled;
}
Then, add the following code which will decide to steal the event from the item children and give it to our onTouchEvent, or let it be handled by them.
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch( ev.getActionMasked() ){
case MotionEvent.ACTION_DOWN:
mInitialX = ev.getX();
mInitialY = ev.getY();
return false;
case MotionEvent.ACTION_MOVE:
float deltaX = Math.abs(ev.getX() - mInitialX);
float deltaY = Math.abs(ev.getY() - mInitialY);
return ( deltaX > 5 || deltaY > 5 );
default:
return super.onInterceptTouchEvent(ev);
}
}
Finally, don't forget to declare the variables in your class:
private float mInitialX;
private float mInitialY;
Since Google introduced Android Support Library v7 21.0.0, you can use RecyclerView to scroll items horizontally. The RecyclerView widget is a more advanced and flexible version of ListView.
To use RecyclerView, just add dependency:
com.android.support:recyclerview-v7:23.0.1
Here is a sample:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
MyAdapter adapter = new MyAdapter(myDataset);
recyclerView.setAdapter(adapter);
}
}
More info about RecyclerView:
https://developer.android.com/training/material/lists-cards.html
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html
This is a little (very) late, but I'm posting this in case someone comes by this later.
The Support Library as of the Android L preview has a RecyclerView that does exactly what you want.
Right now, you can only get it through the L preview SDK and you need to set your minSdk to L. But you can copy all of the necessary files into your project and use them that way until L is officially out.
You can download the preview docs here.
Warning: The API for Recycler View may change and it may have bugs.
Updated
The source code for horizontal listview is:
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView myList = findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);
Download the jar file from here
now put it into your libs folder, right click it and select 'Add as library'
now in main.xml put this code
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/hlistview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
now in Activity class if you want Horizontal Listview with images then put this code
HorizontalListView hListView = (HorizontalListView) findViewById(R.id.hlistview);
hListView.setAdapter(new HAdapter(this));
private class HAdapter extends BaseAdapter {
LayoutInflater inflater;
public HAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Const.template.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listinflate, null);
holder = new HViewHolder();
convertView.setTag(holder);
} else {
holder = (HViewHolder) convertView.getTag();
}
holder.img = (ImageView) convertView.findViewById(R.id.image);
holder.img.setImageResource(Const.template[position]);
return convertView;
}
}
class HViewHolder {
ImageView img;
}
Its actually very simple:
simply Rotate the list view to lay on its side
mlistView.setRotation(-90);
Then upon inflating the children, that should be inside the getView method. you rotate the children to stand up straight:
mylistViewchild.setRotation(90);
Edit:
if your ListView doesnt fit properly after rotation, place the ListView inside this RotateLayout like this:
<com.github.rongi.rotate_layout.layout.RotateLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:angle="90"> <!-- Specify rotate angle here -->
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</com.github.rongi.rotate_layout.layout.RotateLayout>
My solution is to simply use ViewPager widget. It isn't center-locked as Gallery and has a built-in features for recycling views (as ListView). You may see similar approach at Google Play app, whenever you deal with horizontally scrollable lists.
You just need to extend PagerAdapter and perform a couple of tweaks there:
public class MyPagerAdapter extends PagerAdapter {
private Context mContext;
public MyPagerAdapter(Context context) {
this.mContext = context;
}
// As per docs, you may use views as key objects directly
// if they aren't too complex
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.item, null);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
// Important: page takes all available width by default,
// so let's override this method to fit 5 pages within single screen
#Override
public float getPageWidth(int position) {
return 0.2f;
}
}
As result, you'll have horizontally scrollable widget with adapter, like this:
Note: Android now supports horizontal list views using RecyclerView, so now this answer is deprecated, for information about RecyclerView :
https://developer.android.com/reference/android/support/v7/widget/RecyclerView
I have developed a logic to do it without using any external horizontal scrollview library, here is the horizontal view that I achieved and I have posted my answer here:https://stackoverflow.com/a/33301582/5479863
My json response is this:
{"searchInfo":{"status":"1","message":"Success","clist":[{"id":"1de57434-795e-49ac-0ca3-5614dacecbd4","name":"Theater","image_url":"http://52.25.198.71/miisecretory/category_images/movie.png"},{"id":"62fe1c92-2192-2ebb-7e92-5614dacad69b","name":"CNG","image_url":"http://52.25.198.71/miisecretory/category_images/cng.png"},{"id":"8060094c-df4f-5290-7983-5614dad31677","name":"Wine-shop","image_url":"http://52.25.198.71/miisecretory/category_images/beer.png"},{"id":"888a90c4-a6b0-c2e2-6b3c-561788e973f6","name":"Chemist","image_url":"http://52.25.198.71/miisecretory/category_images/chemist.png"},{"id":"a39b4ec1-943f-b800-a671-561789a57871","name":"Food","image_url":"http://52.25.198.71/miisecretory/category_images/food.png"},{"id":"c644cc53-2fce-8cbe-0715-5614da9c765f","name":"College","image_url":"http://52.25.198.71/miisecretory/category_images/college.png"},{"id":"c71e8757-072b-1bf4-5b25-5614d980ef15","name":"Hospital","image_url":"http://52.25.198.71/miisecretory/category_images/hospital.png"},{"id":"db835491-d1d2-5467-a1a1-5614d9963c94","name":"Petrol-Pumps","image_url":"http://52.25.198.71/miisecretory/category_images/petrol.png"},{"id":"f13100ca-4052-c0f4-863a-5614d9631afb","name":"ATM","image_url":"http://52.25.198.71/miisecretory/category_images/atm.png"}]}}
Layout file :
<?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"
android:weightSum="5">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4" />
<HorizontalScrollView
android:id="#+id/horizontalScroll"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
class file:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll);
for (int v = 0; v < collectionInfo.size(); v++) {
/*---------------Creating frame layout----------------------*/
FrameLayout frameLayout = new FrameLayout(ActivityMap.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, getPixelsToDP(90));
layoutParams.rightMargin = getPixelsToDP(10);
frameLayout.setLayoutParams(layoutParams);
/*--------------end of frame layout----------------------------*/
/*---------------Creating image view----------------------*/
final ImageView imgView = new ImageView(ActivityMap.this); //create imageview dynamically
LinearLayout.LayoutParams lpImage = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
imgView.setImageBitmap(collectionInfo.get(v).getCatImage());
imgView.setLayoutParams(lpImage);
// setting ID to retrieve at later time (same as its position)
imgView.setId(v);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getting id which is same as its position
Log.i(TAG, "Clicked on " + collectionInfo.get(v.getId()).getCatName());
// getting selected category's data list
new GetSelectedCategoryData().execute(collectionInfo.get(v.getId()).getCatID());
}
});
/*--------------end of image view----------------------------*/
/*---------------Creating Text view----------------------*/
TextView textView = new TextView(ActivityMap.this);//create textview dynamically
textView.setText(collectionInfo.get(v).getCatName());
FrameLayout.LayoutParams lpText = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER);
// Note: LinearLayout.LayoutParams 's gravity was not working so I putted Framelayout as 3 paramater is gravity itself
textView.setTextColor(Color.parseColor("#43A047"));
textView.setLayoutParams(lpText);
/*--------------end of Text view----------------------------*/
//Adding views at appropriate places
frameLayout.addView(imgView);
frameLayout.addView(textView);
linearLayout.addView(frameLayout);
}
private int getPixelsToDP(int dp) {
float scale = getResources().getDisplayMetrics().density;
int pixels = (int) (dp * scale + 0.5f);
return pixels;
}
trick that is working here is the id that I have assigned to ImageView "imgView.setId(v)" and after that applying onClickListener to that I am again fetching the id of the view....I have also commented inside the code so that its easy to understand,
I hope this may be very useful...
Happy Coding... :)
This isn't much of an answer, but how about using a Horizontal Scroll View?
You can use RecyclerView in the support library. RecyclerView is a generalized version of ListView that supports:
A layout manager for positioning items
Default animations for common
item operations
Android Recycler View Docs
I've done a lot of searching for a solution to this problem. The short answer is, there is no good solution, without overriding private methods and that sort of thing. The best thing I found was to implement it myself from scratch by extending AdapterView. It's pretty miserable. See my SO question about horizontal ListViews.
I had to do the same for one of my projects and I ended up writing my own as well. I called it HorzListView is now part of my open source Aniqroid library.
http://aniqroid.sileria.com/doc/api/ (Look for downloads at the bottom or use google code project to see more download options: http://code.google.com/p/aniqroid/downloads/list)
The class documentation is here: http://aniqroid.sileria.com/doc/api/com/sileria/android/view/HorzListView.html
For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:
<HorizontalScrollView
android:id="#+id/photo_scroll"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="horizontal"
android:visibility="gone">
<LinearLayout
android:id="#+id/imageview_holder"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="match_parent">
</LinearLayout>
</HorizontalScrollView>
An this works perfectly fine for me. In the activity all I have to do is something like the code below:
LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2);
As I said that works for me, and I hope it helps somebody looking to achieve this as well.
well you can always create your textviews etc dynamically and set your onclicklisteners like you would do with an adapter
HorizontialListView can't work when the data in the adapter is involved in another thread. Everything runs 100% on UI thread.This is a big problem in multithread. I think using HorizontialListView is not the best solution for your problem.HorzListView is a better way.You just replace your previous Gallery with HorzListView.You neednot modify the code about the adapter.Then everything goes the way you hope.See https://stackoverflow.com/a/12339708/1525777 about HorzListView.
I had used horizontal listview link in my project & I got good results. I had been used devsmart library initially but it gave me some issues. So best way to use horizontal listview link as it recovered my issues & also I recently launched my app on Google PlayStore using this library & got nice response from users. So I recommend you to use the same library which I mentioned above to show listview horizontally. Enjoy :)
There is a great library for that, called TwoWayView, it's very easy to implement, just include the project library into your work space and add it as a library project to your original project, and then follow the following steps which are originally mentioned here:
First, let's add a style indicating the orientation of the ListView
(horizontal or vertical) in (res/values/styles.xml):
<style name="TwoWayView">
<item name="android:orientation">horizontal</item>
</style>
Then,
In your Layout XML, use the following code to add the TwoWayView:
<org.lucasr.twowayview.TwoWayView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/lvItems"
style="#style/TwoWayView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"
tools:context=".MainActivity" />
and finally, just declare it and deal with it like any regular ListView:
TwoWayView lvTest = (TwoWayView) findViewById(R.id.lvItems);
All the methods of ListView will work here as usual, but there is only one difference I noticed, which is when setting the choice mode, the method setChoiceMode not takes an int value but a value from enum called ChoiceMode, so list_view.setChoiceMode(ListView.CHOICE_MODE_SINGLE); will be lvTest.setChoiceMode(ChoiceMode.SINGLE); // or MULTIPLE or NONE.
You may use ViewFlipper to include the layout XML and add images , listview for each layout XML