How to change images in imageview on fling - java

I have a relative layout which contains an image. I have like 10-20 images in drawable folder and a hashmap which stores these images.
On swiping below the image from left to right, it should change to next image.
On each swipe, it should change to next image from hashmap.
I am completely new to java and android programming and help in any way is appreciated.
This is what I have:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.bschiranth.homework2_chiranthbs.MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/alice"
android:onClick="onClick"
android:clickable="true"
android:src="#drawable/alice"/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/zoombar"
android:max="100"
android:progress="50"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
and my java:
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d("fling", "doing fling");
MovieData movieData = new MovieData();
HashMap hashMap = new HashMap();
for(int i=1;i<movieData.getSize();i++)
{
hashMap = movieData.getItem(i);
}
if(event1.getX()-event2.getX()> SWIPE_MIN_DISTANCE && Math.abs(velocityX)>SWIPE_THRESHOLD_VELOCITY)
{
Toast.makeText(Activity_Control.this,
"its flinging right to left", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.avatar);
}
if(event2.getX()-event1.getX()> SWIPE_MIN_DISTANCE && Math.abs(velocityX)>SWIPE_THRESHOLD_VELOCITY)
{
Toast.makeText(Activity_Control.this,
"its flinging left to right", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.avengers);
}
return true;
}

Better you can use view pager instead of imageview
<?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:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/myfivepanelpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ViewPagerAdapter.java
import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class ViewPagerAdapter extends PagerAdapter {
Activity activity;
int imageArray[];
public ViewPagerAdapter(Activity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
PageIndicatorActivity.java
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}

This can be done by ViewFlipper as described below.
This is your Activity.xml file
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view_flipper"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HowToUseActivity" >
<ImageView
android:id="#+id/imageHowToUse"
android:contentDescription="#string/app_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#mipmap/screen_1" />
</ViewFlipper>
declare required variables in your activity class
private int number = 0;
private float initialX;
private ImageView imageView;
in your Activity's onCreate(...) method retrieve the ImageView
imageView = (ImageView) findViewById(R.id.imageHowToUse);
override the method onTouchEvent(...) in same activity
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = event.getX();
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX();
if (initialX > finalX) {
if (number >= 3) {
break;
}
next();
} else {
if(number <= 0) {
break;
}
previous();
}
break;
}
return false;
}
private void next() {
number++;
imageView.setImageResource(getImage());
}
private void previous() {
number--;
imageView.setImageResource(getImage());
}
then write method getImage() to get next image you want to display
private int getImage() {
int resource = R.mipmap.screen_1;
switch(number) {
case 0:
resource = R.mipmap.screen_1;
break;
case 1:
resource = R.mipmap.screen_2;
break;
case 2:
resource = R.mipmap.screen_3;
break;
}
return resource;
}
this is working code in my project. It'll help you.
NOTE : R.mipmap.screen_* is the image resource present in my resource directory.

Related

How to set up onItemClickListener

I set up a Listview in Android Studio but need help with coding a OnItemClickListner.
I have tried the code, but doesn't seem to work.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayList<Object> list = new ArrayList<>();
list.add(new LTCItem("30.06 Sign Violations","Submit A Complaint To Texas Attorney General",R.drawable.gavel));
list.add(new LTCItem("U.S. & Texas LawShield","Legal Defense For Self Defense",R.drawable.lawshield));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
Below is my list_view file. Where in the file do block descendantFocusability as suggested? Do I put it under listView? Sorry I am learning .
<?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="match_parent"
android:alwaysDrawnWithCache="true"
android:background="#000000"
android:padding="8dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/itemListViewImgIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#+id/itemListViewImgIcon"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/itemListViewTxtTopicName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/itemListViewTxtTopicSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemListViewTxtTopicName"
</RelativeLayout>
Ok I added the adapter code which is a Java Class item. Where do I add the code here?
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
Your ListView element doesn't have an ID, you should add android:id="#+id/list_view" to it in the XML file.
Here is an example:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As your list view contains focusable elements, you need to write this piece of code in parent layout in your list view item xml file
android:descendantFocusability="blocksDescendants"

Use TabAdapter for scroll horizontal and vertical

Basically I already have a HorizontalAdapters which means I can only swipe left and right and in those swipes I have 3 pages.
public class HorizontalViewPager extends FragmentPagerAdapter {
public HorizontalViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return ChatFragment.create();
case 1:
return EmptyFragment.create();
case 2:
return StoryFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
Now I'm trying to add two more pages on top and below my EmptyFragment so when I swipe up it goes to another page and also when I swipe down.
I have my two fragments that I want to put on top and below my emptyfragment.
This is my MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//VerticalViewPager
me.kaelaela.verticalviewpager.VerticalViewPager verticalViewPager = findViewById(R.id.am_scrollView);
VerticalViewPager scrollViewAdapter = new VerticalViewPager(getSupportFragmentManager());
verticalViewPager.setAdapter(scrollViewAdapter);
verticalViewPager.setPageTransformer(false, new DefaultTransformer());
//HorizontalViewPager
View background = findViewById(R.id.am_background_view);
ViewPager viewPager = findViewById(R.id.am_view_pager);
HorizontalViewPager adapter = new HorizontalViewPager(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1);
And this is my EmptyFragment
public class EmptyFragment extends Fragment {
public static EmptyFragment create(){
return new EmptyFragment();
}
If you dont under stand what I'm trying to do its basically just a page that you can swipe left,right,up,and down and it views different pages.
MainLayout File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="c.kristofer.jax2.MainActivity">
<View
android:id="#+id/am_background_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"/>
<me.kaelaela.verticalviewpager.VerticalViewPager
android:id="#+id/am_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v4.view.ViewPager
android:id="#+id/am_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
And my two layout files that I want to put above and below my emptyfragment
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
</LinearLayout>
And
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/yellow">
</LinearLayout>
I answer the exact same question here. Probably you guys do the same class, so be attention with ctrl+c and ctrl+v code.
I will copy
Getting the base from here.
Create a GestureDetectorCompat object
GestureDetectorCompat gestureDetectorCompat;
and override onTouchEvent in the activity
#Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetectorCompat.onTouchEvent(event);
return true;
}
or if you want to detect on some view then you can Override onTouch
someView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
gestureDetectorCompat.onTouchEvent(motionEvent);
return false;
}
});
and initialize gestureDetectorCompat as follows somewhere preferably in onCreate() and you are done.
gestureDetectorCompat = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
float angle = (float) Math.toDegrees(Math.atan2(e1.getY() - e2.getY(), e2.getX() - e1.getX()));
if (angle > -45 && angle <= 45) {
if(goRight != 5) mainContainer.setCurrentItem(goRight);
return true;
}
if (angle >= 135 && angle < 180 || angle < -135 && angle > -180) {
if(goLeft != 5) mainContainer.setCurrentItem(goLeft);
return true;
}
if (angle < -45 && angle >= -135) {
if(goUp != 5)mainContainer.setCurrentItem(goUp);
return true;
}
if (angle > 45 && angle <= 135) {
if(goDown != 5)mainContainer.setCurrentItem(goDown);
return true;
}
return false;
}
});
Then you can use mainContainer.setCurrentItem(number); to go to other position/fragment.
Don't forget that the number change if you are in different number. Like this
switch(adapter.getCurrentItem()){
case 0:
goRight = 2;
goLeft = 4;
goUp = 3;
goDown = 1;
break;
case 1:
goRight = 5;
goLeft = 5;
goUp = 0;
goDown = 5;
break;
case 2:
goRight = 5;
goLeft = 0;
goUp = 5;
goDown = 5;
break;
case 3:
goRight = 5;
goLeft = 5;
goUp = 5;
goDown = 0;
break;
case 4:
goRight = 0;
goLeft = 5;
goUp = 5;
goDown = 5;
break;
}
When you are in the fragment 4 you can only go to 0, not 2 if you swipe left-right.
And this should be your adapter
public class SwipeViewPager extends FragmentPagerAdapter {
public SwipeViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return EmptyFragment.create();
case 1:
return StoryFragment.create();
case 2:
return ExtrasFragment.create();
case 3:
return ChatFragment.create();
case 4:
return SettingsFragment.create();
}
return null;
}
#Override
public int getCount() {
return 5;
}
Create one more Fragment with VerticalViewPager inside it and add top, empty and bottom to view pager and set default page to empty page fragment
MainActivity layout should be as below
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="c.kristofer.jax2.MainActivity">
<View
android:id="#+id/am_background_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"/>
<android.support.v4.view.ViewPager
android:id="#+id/am_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
The HorizontalViewPager should be like below see VerticalScrollFragment
public class HorizontalViewPager extends FragmentPagerAdapter {
public HorizontalViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ChatFragment.create();
case 1:
return VerticalScrollFragment.create();
case 2:
return StoryFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Then VerticalFragment layout vertical.xml file will be like this
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="c.kristofer.jax2.MainActivity">
<me.kaelaela.verticalviewpager.VerticalViewPager
android:id="#+id/am_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Then VerticalFragment class will be like below
public class VerticalScrollFragment extends Fragment {
VerticalViewPager verticalViewPager;
VerticalViewPagerAdapter verticalPageAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vertical, null);
verticalViewPager = view.findViewById(R.id.am_scrollView);
verticalPageAdapter = new VerticalViewPagerAdapter(getChildFragmentManager());
verticalViewPager.setAdapter(verticalPageAdapter)
return inflater.inflate(R.layout.vertical, null);
}
public class VerticalViewPagerAdapter extends FragmentPagerAdapter {
public HorizontalViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TopFragment.create();
case 1:
return EmptyFragment.create();
case 2:
return BottomFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
}

How to show viewpager with margin or different design

I am using view pager to show some fragments.
I tried to achieve this by referring this : Android ViewPager - Smooth Transition for this Design
My View pager containing layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical"
android:weightSum="1"
tools:context="com.tpayerapp.Fragments.DepositMoneyFragment">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:clipToPadding="false"
android:layout_above="#+id/indicator"
android:layout_below="#+id/tabs"
android:padding="80dp" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="false"
app:ci_drawable="#drawable/radius"
app:ci_drawable_unselected="#drawable/grey_radius"
app:ci_height="6dp"
app:ci_width="6dp">
</me.relex.circleindicator.CircleIndicator>
Fragment 1 layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
tools:context="com.tpayerapp.Fragments.PayPalFragment">
<ImageView
android:id="#+id/imageView25"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="false"
android:layout_alignParentTop="false"
android:layout_alignWithParentIfMissing="false"
android:layout_centerHorizontal="false"
android:layout_centerInParent="true"
android:background="#color/colorAccent"
app:srcCompat="#drawable/paypal" />
View pager fragment java code:
public class DepositMoneyFragment extends Fragment {
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_deposit_money, container, false);
setUpUI(view);
return view;
}
public void setUpUI(View view) {
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
int pageWidth = viewPager.getMeasuredWidth() - viewPager.getPaddingLeft() - viewPager.getPaddingRight();
int pageHeight = viewPager.getHeight();
int paddingLeft = viewPager.getPaddingLeft();
float transformPos = (float) (page.getLeft() - (viewPager.getScrollX() + paddingLeft)) / pageWidth;
final float normalizedposition = Math.abs(Math.abs(transformPos) - 1);
page.setAlpha(normalizedposition + 0.5f);
int max = -pageHeight / 10;
if (transformPos < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
page.setTranslationY(0);
} else if (transformPos <= 1) { // [-1,1]
page.setTranslationY(max * (1-Math.abs(transformPos)));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
page.setTranslationY(0);
}
}
});
}
#Override
public void onResume() {
super.onResume();
((OnFragmentTitleChangeListener) getActivity()).onFragmentTitle(getResources().getString(R.string.deposite));
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PayPalFragment(), "");
adapter.addFragment(new PayStackFragment(), "");
adapter.addFragment(new NIBBSFragment(), "");
viewPager.setAdapter(adapter);
}
}
What needs to be done to get this design? Please help. Thank you..
Try Change margin to padding
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="40dp"
android:paddingRight="40dp"
tools:context="com.tpayerapp.Fragments.PayPalFragment">
<ImageView
android:id="#+id/imageView25"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="false"
android:layout_alignParentTop="false"
android:layout_alignWithParentIfMissing="false"
android:layout_centerHorizontal="false"
android:layout_centerInParent="true"
android:background="#color/colorAccent"
app:srcCompat="#drawable/paypal" />
try this link carousel layout with viewpager, if you need more code related to this view, this are main classes you need.
CarouselLinearLayout.java
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;
public class CarouselLinearLayout extends LinearLayout {
private float scale = CarouselPagerAdapter.BIG_SCALE;
public CarouselLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CarouselLinearLayout(Context context) {
super(context);
}
public void setScaleBoth(float scale) {
this.scale = scale;
this.invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// The main mechanism to display scale animation, you can customize it as your needs
int w = this.getWidth();
int h = this.getHeight();
canvas.scale(scale, scale, w/2, h/2);
}
}
CarouselPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class CarouselPagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
public final static float BIG_SCALE = 1.0f;
public final static float SMALL_SCALE = 0.7f;
public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
private MainActivity context;
private FragmentManager fragmentManager;
private float scale;
public CarouselPagerAdapter(MainActivity context, FragmentManager fm) {
super(fm);
this.fragmentManager = fm;
this.context = context;
}
#Override
public Fragment getItem(int position) {
// make the first pager bigger than others
try {
if (position == MainActivity.FIRST_PAGE)
scale = BIG_SCALE;
else
scale = SMALL_SCALE;
position = position % MainActivity.count;
} catch (Exception e) {
e.printStackTrace();
}
return ItemFragment.newInstance(context, position, scale);
}
#Override
public int getCount() {
int count = 0;
try {
count = MainActivity.count * MainActivity.LOOPS;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return count;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
try {
if (positionOffset >= 0f && positionOffset <= 1f) {
CarouselLinearLayout cur = getRootView(position);
CarouselLinearLayout next = getRootView(position + 1);
cur.setScaleBoth(BIG_SCALE - DIFF_SCALE * positionOffset);
next.setScaleBoth(SMALL_SCALE + DIFF_SCALE * positionOffset);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#SuppressWarnings("ConstantConditions")
private CarouselLinearLayout getRootView(int position) {
return (CarouselLinearLayout) fragmentManager.findFragmentByTag(this.getFragmentTag(position))
.getView().findViewById(R.id.root_container);
}
private String getFragmentTag(int position) {
return "android:switcher:" + context.pager.getId() + ":" + position;
}
}
I see you have hard coded the viewPager height to android:layout_height="200dp". Can you try using android:layout_height="match_parent" instead?

Unable to listen to setOnItemClickListener in ListView - Android

I have a ListView in my MainActivity which has a customAdapter to it. I am implementing a slider on each of the list items. I have also attached a footerView to my listView. Now my problem is that, the setOnClickListener is not fired, and I am not able to print the position's of the listView. It only print's for the footerView alone, which I have attached.
The code for MainActivity is
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
Then the code for my CustomAdapter is
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
Then finally the ViewPagerAdapter code is
public class MyViewPager extends ViewPager {
private static final String TAG = "MyViewPager";
private float xDown;
private float xMove;
private float yDown;
private float yMove;
private boolean isScroll = false;
private int selfIndex;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSelfIndex(int index) {
selfIndex = index;
}
public int getSelfIndex() {
return selfIndex;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.v(TAG, "on intercept");
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v(TAG, "on dispatch");
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.v(TAG, "action down: " + xDown + ", " + yDown);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
xMove = ev.getRawX();
yMove = ev.getRawY();
Log.v(TAG, "action move: " + xMove + ", " + yMove);
if (isScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
if (Math.abs(yMove - yDown) < 5 && Math.abs(xMove - xDown) > 20) {
isScroll = true;
} else {
return false;
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
isScroll = false;
}
return super.dispatchTouchEvent(ev);
}
}
The MainActivity layout is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
The layout for listview_item is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
Added all XML Layouts
listview_item_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:minHeight="100dp" >
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/main_list_text"
android:textSize="48sp"
android:textStyle="bold" />
<EditText
android:id="#+id/et_input_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_contact_hint"
android:textColorHint="#color/main_list_text"
android:textColor="#color/main_list_text"
android:textSize="30sp"
android:textStyle="bold"
android:inputType="textCapCharacters"
android:background="#null"
android:textCursorDrawable="#null"
android:singleLine="true"
android:imeOptions="actionDone"
android:visibility="gone" />
</RelativeLayout>
listview_item_slide
<?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:minHeight="100dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_menu_cancel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:background="#color/gold"
android:gravity="center"
android:text="#string/cancel"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_delete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/green"
android:gravity="center"
android:text="#string/delete"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_block"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/royalblue"
android:gravity="center"
android:text="#string/block"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
</LinearLayout>
Please help me to listen to the onItemClickListener in the MainActivity's list. I am not able to figure out where I went wrong. Thanks in advance.
you have to put your "setOnItemClickListener" to your Adapter class insted of MainActivity.
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
ViewHolder holder;
View iView = convertView;
if (convertView == null) {
iView = inflater.inflate(R.layout.listview_item, parent, false);
holder = new ViewHolder();
holder.txt_name = (TextView) iView.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(
context.getAssets(), "KozGoPr6N-Regular.otf");
holder.txt_name.setTypeface(custom_fontG);
holder.txt_desc = (TextView) iView.findViewById(R.id.detail);
holder.ivProfile = (ImageView) iView.findViewById(R.id.flag);
iView.setTag(holder);
} else {
holder = (ViewHolder) iView.getTag();
}
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// Capture position and set results to the TextViews
holder.txt_name.setText(resultp.get(OurTeam.TAG_NAME));
holder.txt_desc.setText(resultp.get(OurTeam.TAG_DETAIL));
imageLoader.displayImage(TAG_IMAGEURL + resultp.get((OurTeam.TAG_IMG)),
holder.ivProfile, options);
// Capture ListView item click
iView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
// your code
}
});
return iView;
}
At a time you can handle click event either in Adapter class of in Activity. in your case you are doing both.
And to manage
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
Write above on click event of what ever is main view in listview_item layout (Do not forget to pass addContact and inputName views to your CustomAdapter).
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
/* mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});*/
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
and Adapter Class was..
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code here for list item click listener...
}
})
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
add this below line in your listview_item parent layout only.
android:descendantFocusability="blocksDescendants"
actually when the list item contains a element which can get focus then list item click listener not work.
Add this to the parent of your Listview and parent of your listview_item and try again:
android:descendantFocusability="blocksDescendants"
Like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
and this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:descendantFocusability="blocksDescendants"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
If this does not work, call isFocusable() on your EditText and TextView
addContact.isFocusable(false);
inputName.isFocusable(false);
I am guessing you made a common error. Please check/try both changes.
1) add android:descendantFocusability="blocksDescendants" into the ListView UI ("#+id/lv_main").
Note: If this and 2nd suggestion does not work, then the Listview layout may need rework.
2) mainListView.setItemsCanFocus(false);
Note: The Listview may be confused with focusing on an item in the UI.
I think the suggested code by "Nirmal Shethwala" looks good. It has the if/else block for if (convertView == null).
EDIT: I noticed you inflated 3 xml layout files in getView(). You can only have one, and that is listview_item in your code. I know this is not well documented. I have tried this in the past. The reason is getView() method has to return only one view, and your code return convertView; like me.
Sorry I know this will take some modifications in your layout.

ListView setOnItemClickListener is not fired / called

I know this question is asked several times here, and i go through all the answer and tried implementing it in my code, but the result is fail. That's why i have posted a new question to get my code run. Question is simple whenever i want to trigger listView.setOnItemClickListener(this). It is not fired. I tried each suggestion given in stackoverflow but not able to solve the issue.
Code i used are
visitor_list_fragment.xml 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" >
<TextView
android:id="#+id/node_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:textIsSelectable="false"
android:textSize="20sp" />
<ListView
android:id="#+id/visitor_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:cacheColorHint="#00000000"
android:dividerHeight="5dp"
android:listSelector="#00000000"
android:scrollingCache="true"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
visitor_list_item.xml 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="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/photo_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:contentDescription="#string/image_name"
android:focusable="false" />
<TextView
android:id="#+id/profile_info_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:focusable="false"
android:textColor="#android:color/black"
android:textIsSelectable="false"
android:textSize="20sp" />
</LinearLayout>
Code where i called onItemClickListener
public class VisitorListFragment extends Fragment implements OnItemClickListener
{
private TextView m_NodeName;
private ListView m_VisitorListView;
private VisitorListAdapter m_VisitorNodeListAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.visitor_list_fragment, null);
m_NodeName = (TextView)view.findViewById(R.id.node_name_textView);
m_VisitorNodeListAdapter = new VisitorListAdapter(getActivity().getApplicationContext());
m_VisitorListView = (ListView)view.findViewById(R.id.visitor_list_view);
// Displaying header & footer in the list-view
TextView header = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
header.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addHeaderView(header, null, false);
TextView footer = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
footer.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addFooterView(footer, null, false);
m_VisitorListView.setAdapter(m_VisitorNodeListAdapter);
m_VisitorListView.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String nodeName = m_VisitorNodeListAdapter.getNodeName(position);
System.out.println(nodeName);
}
}
AdapterClass
public class VisitorListAdapter extends BaseAdapter
{
private HashMap<String, String> m_ProfileImagePath;
private HashMap<String, String> m_ProfileInfo;
private ArrayList<String> m_NodeName;
private LayoutInflater m_Inflater=null;
public VisitorListAdapter(Context context)
{
super();
m_ProfileImagePath = new HashMap<String, String>();
m_ProfileInfo = new HashMap<String, String>();
m_NodeName = new ArrayList<String>();
m_Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getItem(int arg0)
{
return null;
}
public int getCount()
{
return m_NodeName.size();
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int position)
{
return false;
}
public String getNodeName(int position)
{
return m_NodeName.get(position);
}
public class ViewHolder
{
TextView profileInfoTextView;
ImageView profileImageView;
}
public void addProfileInfo(String nodeName, String profileInfo)
{
boolean found = false;
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
found = true;
}
}
if(found == false)
{
m_NodeName.add(nodeName);
m_ProfileInfo.put(nodeName, profileInfo);
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
}
public void addProfileImagePath(String nodeName, String profileInfoImagePath)
{
m_ProfileImagePath.put(nodeName, Utilities.CHORD_FILE_PATH + "/" + profileInfoImagePath);
notifyDataSetChanged();
}
public void removeNode(String nodeName)
{
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
m_NodeName.remove(i);
m_ProfileInfo.remove(nodeName);
m_ProfileImagePath.remove(nodeName);
}
}
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public void clearAll()
{
m_ProfileImagePath.clear();
m_NodeName.clear();
m_ProfileInfo.clear();
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = m_Inflater.inflate(R.layout.visitor_list_item, null);
holder.profileImageView = (ImageView)convertView.findViewById(R.id.photo_view);
holder.profileInfoTextView = (TextView)convertView.findViewById(R.id.profile_info_textview);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
// Put the code in an async task
new ImageLoaderTask(position, holder).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return convertView;
}
class ImageLoaderTask extends AsyncTask<URL, Integer, Long>
{
private int position;
private ViewHolder holder;
ImageLoaderTask(int position, ViewHolder holder)
{
this.position = position;
this.holder = holder;
}
#Override
protected void onPreExecute()
{
String loadPath = m_ProfileImagePath.get(m_NodeName.get(position));
Bitmap bitmap = BitmapFactory.decodeFile(loadPath);
if(bitmap != null)
{
holder.profileImageView.setImageBitmap(bitmap);
}
holder.profileInfoTextView.setText(m_ProfileInfo.get(m_NodeName.get(position)));
}
#Override
protected Long doInBackground(URL... urls)
{
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
}
#Override
protected void onPostExecute(Long result)
{
}
}
}
public boolean isEnabled(int position)
{
return false;
}
This should be true for all active elements!
Try removing
android:focusable="false" and
android:textIsSelectable="false"
from listView_item.xml file...
Check if your m_VisitorListView isn't null (debugging mode).
Check the import onItemClick, should be AdapterView.OnItemClickListener
If you still facing this issue try implementing it anonymously:
m_VisitorListView .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
} );

Categories

Resources