Error in the ViewPager - android

I use PagerView in my application. But I have mistake. I load image in each pages. On all pages I see my images. but the page that has a position 0 in pagerAdapter is empty always. What I do not correctly?
public class MainActivity extends ActionBarActivity {
String TAG = "State";
static ViewPager pager;
static PagerAdapter pagerAdapter;
public static MainActivity activity;
static final int PAGE_COUNT = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
pager = (ViewPager) findViewById(R.id.pager);
pager.setOffscreenPageLimit(0);
final ArrayList<String> imagePaths = new ArrayList<String>();
imagePaths.add("http://tlt.ru/uploads/2014/05/94e1e91067997356912d68e0acc36d31_x240.jpg");
imagePaths.add("http://tlt.ru/uploads/2014/05/d2cb96bd2e26fd19c4ec5a125d8a6ada_x240.jpg");
imagePaths.add("http://tlt.ru/uploads/2014/05/6bc17baed9ef08a7aa1c68db2dcd650c_x240.jpg");
pagerAdapter = new FullScreenImageAdapter(activity, imagePaths);
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Log.d(TAG, "onPageSelected, position = " + position);
// update();
FullScreenImageAdapter.startRefresh(imagePaths.get(position));
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
pager.setCurrentItem(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static void update() {
// pager.setAdapter(pagerAdapter);
// refreshView(pager.getCurrentItem());
pagerAdapter.notifyDataSetChanged();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
public static TouchImageView imgDisplay;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.fragment, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imageView1);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Refresh mt = new Refresh();
try {
mt.execute(new URL(_imagePaths.get(position)));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 300);
// imgDisplay.setImageBitmap(bitmap);
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
public static void startRefresh(final String url) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Refresh mt = new Refresh();
try {
mt.execute(new URL(url));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
How I can load image in page[0]?

I thikn the problem is in the getItemPosition, try this:
#Override
public int getItemPosition (Object object){
int index = _imagePaths.indexOf(object);
if (index == -1)
return POSITION_NONE;
else
return index;
}

The problem is with the position, you can find a better solution for pager here. You need to Modify activity_main.xml to include android.support.v4.view.ViewPager in layout.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/myviewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And MainActivity.java
package com.example.androidviewpagerapp;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
public class MainActivity extends Activity {
ViewPager viewPager;
MyPagerAdapter myPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.myviewpager);
myPagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(myPagerAdapter);
}
private class MyPagerAdapter extends PagerAdapter{
int NumberOfPages = 5;
int[] res = {
android.R.drawable.ic_dialog_alert,
android.R.drawable.ic_menu_camera,
android.R.drawable.ic_menu_compass,
android.R.drawable.ic_menu_directions,
android.R.drawable.ic_menu_gallery};
int[] backgroundcolor = {
0xFF101010,
0xFF202020,
0xFF303030,
0xFF404040,
0xFF505050};
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView textView = new TextView(MainActivity.this);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setText(String.valueOf(position));
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(res[position]);
LayoutParams imageParams = new LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(imageParams);
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
layout.setBackgroundColor(backgroundcolor[position]);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
layout.addView(imageView);
final int page = position;
layout.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Page " + page + " clicked",
Toast.LENGTH_LONG).show();
}});
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
}

Related

How to enable CardView in ViewPager

I have tried using CardView in ViewPager and everytime I swipe left/right on CardView it goes to the next screen. I want the card to delete itself then. Currently as a standalone both are working fine but when I combine then only viewpager is working and not cardswipe dismiss.
I tried to disable ViewPager with the code below but this code also disables CardView swipe gestures. How can I make only CardView to have gesture and when you swipe in between 2 cards then its should have ViewPager as its not connected to card element.
Or disable ViewPager completely and use it as buttons and enable swipe on CardView. I really appreciate any help. Thanks in Advance.
FYI: I have tried android_horizontal_listview in ViewPager and that works fine and exactly like this.
For ViewPager:
mPager.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
For CardView:
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(mRecyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
mRecyclerView.addOnItemTouchListener(swipeTouchListener);
Mainactivity.java
public class MainActivity extends Activity implements ActionBar.TabListener {
ViewPager vp;
View viewpager_layout_1;
View viewpager_layout_2;
View viewpager_layout_3;
ActionBar.Tab tab_1;
ActionBar.Tab tab_2;
ActionBar.Tab tab_3;
ActionBar bar;
/////
String jsonstring1;
CardViewAdapter spinnerArray;
ImageLoader imageLoader = ImageLoader.getInstance();//
DisplayImageOptions options;
ArrayList<HashMap<String, String>> array_list1;
RecyclerView recyclerView;
RelativeLayout re1;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mContext = this;
viewpager_layout_1 = new View(mContext);
viewpager_layout_1 = getLayoutInflater().inflate(R.layout.sample1, null);
viewpager_layout_3 = new View(mContext);
viewpager_layout_3 = getLayoutInflater().inflate(R.layout.sample2, null);
viewpager_layout_2 = new View(mContext);
viewpager_layout_2 = getLayoutInflater().inflate(R.layout.sample3, null);
vp = (ViewPager) findViewById(R.id.vp);
bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
Vector<View> pages = new Vector<View>();
pages.add(viewpager_layout_1);
pages.add(viewpager_layout_3);
pages.add(viewpager_layout_2);
CustomPagerAdapter adapter = new CustomPagerAdapter(mContext, pages);
vp.setAdapter(adapter);
vp.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
bar.setSelectedNavigationItem(position);
}
});
tab_1 = bar.newTab();
tab_1.setCustomView(R.layout.tab_layout_1);
tab_1.setTabListener(this);
bar.addTab(tab_1);
tab_2 = bar.newTab();
tab_2.setCustomView(R.layout.tab_layout_2);
tab_2.setTabListener(this);
bar.addTab(tab_2);
tab_3 = bar.newTab();
tab_3.setCustomView(R.layout.tab_layout_3);
tab_3.setTabListener(this);
bar.addTab(tab_3);
////
imageLoader.init(ImageLoaderConfiguration.createDefault(MainActivity.this));
jsonstring1 = "[{\"category\":\"1\",\"no\":\"1\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/c/c3/Jordan_by_Lipofsky_16577.jpg\"},{\"category\":\"2\",\"no\":\"2\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Basketball_World_Cup_2014.jpg/800px-Basketball_World_Cup_2014.jpg\"},{\"category\":\"3\",\"no\":\"3\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/4/4e/Basketball_Goal.jpg\"},{\"category\":\"4\",\"no\":\"4\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/1/10/Basketball_through_hoop.jpg\"}]";
//////////
array_list1 = new ArrayList<HashMap<String, String>>();
JSONArray arr = null;
try {
arr = new JSONArray(jsonstring1);
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
String category = e1.getString("category").trim();
String no = e1.getString("no").trim();
String image = e1.getString("image").trim();
HashMap<String, String> map = new HashMap<String, String>();
map.put("category", category);
map.put("no", no);
map.put("image", image);
// adding HashList to ArrayList
array_list1.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OnItemTouchListener itemTouchListener = new OnItemTouchListener() {
#Override
public void onCardViewTap(View view, int position) {
Toast.makeText(MainActivity.this, "Tapped " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton1Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button1 in " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton2Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button2 in " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
};
spinnerArray = new CardViewAdapter(itemTouchListener, MainActivity.this, array_list1);
recyclerView = (RecyclerView) viewpager_layout_3.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
SlideInBottomAnimationAdapter alphaAdapter = new SlideInBottomAnimationAdapter(spinnerArray);
ScaleInAnimationAdapter alphaAdapter2 = new ScaleInAnimationAdapter(alphaAdapter);
final AlphaInAnimationAdapter alphaAdapter3 = new AlphaInAnimationAdapter(alphaAdapter2);
alphaAdapter3.setDuration(500);
alphaAdapter3.setFirstOnly(true);
recyclerView.setAdapter(alphaAdapter3);
final SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(recyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// mItems.remove(position);
Toast.makeText(MainActivity.this, array_list1.get(position) + " swiped left", Toast.LENGTH_SHORT).show();
array_list1.remove(position);
alphaAdapter3.notifyItemRemoved(position);
}
alphaAdapter3.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//
Toast.makeText(MainActivity.this, array_list1.get(position) + " swiped right", Toast.LENGTH_SHORT).show();
array_list1.remove(position);
alphaAdapter3.notifyItemRemoved(position);
}
alphaAdapter3.notifyDataSetChanged();
}
});
recyclerView.addOnItemTouchListener(swipeTouchListener);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
vp.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 2) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_2);
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_1);
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_33);
} else if (tab.getPosition() == 1) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_22);
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_1);
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_3);
} else if (tab.getPosition() == 0) {
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_11);
if (tab_2 != null) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_2);
}
if (tab_3 != null) {
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_3);
}
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
}
public interface OnItemTouchListener {
// this will disallow the touch request for parent scroll on touch of child view
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
public void onCardViewTap(View view, int position);
/**
* Callback invoked when the Button1 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton1Click(View view, int position);
/**
* Callback invoked when the Button2 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton2Click(View view, int position);
}
public class CustomPagerAdapter extends PagerAdapter {
private final Context mContext;
private final Vector<View> pages;
public CustomPagerAdapter(Context context, Vector<View> pages) {
this.mContext = context;
this.pages = pages;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View page = pages.get(position);
container.addView(page);
return page;
}
#Override
public int getCount() {
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
ArrayList<HashMap<String, String>> d;
Activity a;
private List<String> cards;
private OnItemTouchListener onItemTouchListener2;
public CardViewAdapter(OnItemTouchListener onItemTouchListener, Activity a, ArrayList<HashMap<String, String>> d) {
// this.cards = cards;
this.onItemTouchListener2 = onItemTouchListener;
this.a = a;
this.d = d;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
// viewHolder.title.setText(cards.get(i));
HashMap<String, String> item = d.get(i);
viewHolder.title.setText(item.get("category"));
imageLoader.displayImage(item.get("image"), viewHolder.im2);
}
#Override
public int getItemCount() {
// return d == null ? 0 : d.size();
return (null != d ? d.size() : 0);
// return d.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
MotionEvent motionEvent;
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
// private RecyclerView mRecyclerView;
private SwipeableRecyclerViewTouchListener.SwipeListener mSwipeListener;
// Transient properties
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
private int mDismissAnimationRefCount = 0;
private float mAlpha;
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private int mAnimatingPosition = ListView.INVALID_POSITION;
private View mDownView;
private boolean mPaused;
private float mFinalDelta;
///
private TextView title;
private Button button1;
private Button button2;
private ImageView im2;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.card_view_title);
im2 = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativelayout_1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:id="#+id/linearlayout_1"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
</RelativeLayout>
sample2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/re1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
To solve this issue I used an ItemTouchHelper provided by Android to easily swipe to delete an item from a RecyclerView.
Please see implementation below:
MainActivity:
Here I have the implementation of the ViewPager and it's child Fragments.
package za.co.gadgetgirl.testcardpager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
Frag1 frag1 = new Frag1();
Frag2 frag2 = new Frag2();
Frag3 frag3 = new Frag3();
adapter.addFragment(frag1, "frag1");
adapter.addFragment(frag2, "frag2");
adapter.addFragment(frag3, "frag3");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Frag1:
On this Fragment I have a RecyclerView that has an ItemTouchHelper attached. The ItemTouchHelper listens for the onSwiped(...) method that is defined in the SimpleCallback interface and I just remove the swiped item in this method.
package za.co.gadgetgirl.testcardpager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Frag1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1, container, false);
final RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
final RVAdapter rvAdapter = new RVAdapter(Person.initializeData());
rv.setAdapter(rvAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
rvAdapter.removeItem(viewHolder.getAdapterPosition());
}
});
itemTouchHelper.attachToRecyclerView(rv);
return v;
}
}
RVAdapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
//...implementation...
public void removeItem(int position) {
persons.remove(position);
notifyItemRemoved(position);
}
}
To use the ItemTouchHelper, you will need the appcompat-v7:22.2.0 dependency and above defined in your app gradle file.
I haven't use SwipeableRecyclerView before so I cannot really say much. I have a problem same as you before. I solve it by handling onTouch event of the base container of fragment (such as LinearLayout,RelativeLayout) and it work for me. Why don't you try this solution and get back to us
For the use case that you are describing, I don't think that ViewPager is the class that you want to use to get your swipe action. It seems to me that the combination of CoordinatorLayout and SwipeDismissBehavior is more appropriate.
EDIT:
See my solution below:
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CardView cardView = (CardView) findViewById(R.id.cardView);
SwipeDismissBehavior<CardView> behavior = new SwipeDismissBehavior();
behavior.setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_START_TO_END);
behavior.setListener(new SwipeDismissBehavior.OnDismissListener() {
#Override
public void onDismiss(View view) {
finish(); // close activity if desired
}
#Override
public void onDragStateChanged(int state) {
}
});
((CoordinatorLayout.LayoutParams) cardView.getLayoutParams()).setBehavior(behavior);
}
}
Also, here are some examples of using the CoordinatorLayout:
How to use SwipeDismissBehavior.OnDismissListener on RecyclerView
CoordinatorLayout using the ViewPager's RecyclerView
https://lab.getbase.com/introduction-to-coordinator-layout-on-android/
http://android-developers.blogspot.co.uk/2015/05/android-design-support-library.html
I haven't been able to find many examples using SwipeDismissBehavior specifically, but the concepts are similar to the links above.
Alternatively, you may also be able to follow the suggestions of a similar post:
Android swipe layout to dismiss to get the results you desire.
Hope this helps.

Want to play sound on viewpager Swipe

i am working on android app which can play background sound whenever image is swipes. I have gone through multiple tutorials & found codes & i tried for the same but it won't work for me. Here is my code which i tried..
package com.android.learning_numbers;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class Numbers extends Activity {
private static final OnPageChangeListener change = null;
public static MediaPlayer mp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
ViewPager viewPager = (ViewPager)findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(change);}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {R.drawable.sun,R.drawable.sky,R.drawable.moon,};
private int[] mAudio= new int[]{R.raw.sun,R.raw.sky,R.raw.moon,};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Numbers.this;
ImageView imageView = new ImageView(context);
int padding =context.getResources().
getDimensionPixelSize(R.dimen.activity_vertical_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public OnPageChangeListener change = new OnPageChangeListener() {
#Override public void onPageSelected(int position) {
Log.d(ACTIVITY_SERVICE, "OnPageSelected");
if
(mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(Numbers.this, mAudio[position]);
mp.start();
}
#Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override public void onPageScrollStateChanged(int state) {}
};
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
As i think here sound is not called by class on image swipe. Is there any error in my code? Because here OnPageChangeListener is not working for me at all. What is the solution for this? How do i modify my sound code that works for me?
Try this code & make changes according to your needs.. It works for me..
public class Alphabets extends Activity {
MediaPlayer mp;
MediaPlayer BG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setOnPageChangeListener(player);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
BG = MediaPlayer.create(this, R.raw.jingle);
BG.setLooping(true);
BG.setVolume(100, 100);
BG.start();
mp = MediaPlayer.create(Alphabets.this, mAudio[0]);
mp.start();
}
#Override
protected void onPause() {
super.onPause();
BG.pause();
}
#Override
protected void onResume() {
super.onResume();
BG.start();
}
private int[] mAudio = new int[]{R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,
R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,R.raw.one,};
private int imageArra[] = {R.drawable.ab,R.drawable.bc,R.drawable.cd,R.drawable.de,R.drawable.ef,R.drawable.fg,R.drawable.gh,R.drawable.hi,R.drawable.ij,R.drawable.jk,R.drawable.kl,R.drawable.lm,R.drawable.mn,
R.drawable.no,R.drawable.op,R.drawable.pq,R.drawable.qr,R.drawable.rs,R.drawable.st,R.drawable.tu,R.drawable.uv,R.drawable.vw,R.drawable.wx,R.drawable.xy,R.drawable.yz,R.drawable.zz};
public OnPageChangeListener player = new OnPageChangeListener()
{
#Override
public void onPageSelected(int arg1)
{
mp = MediaPlayer.create(Alphabets.this, mAudio[arg1]);
mp.stop();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.numbers, menu);
return true;
}
}

Android viewpager activity problems

I've been working on an Android activity which contains a ViewPager with 10 images on it and an Image View below which will display the image of the ViewPager upon click.
When I try to run it after entering through my login screen, the deal crashes.
I'm not sure where are the errors LogCat warns about so if you could help me out I'd be very grateful.
Here are the LogCat messages:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.logger.SecondActivity$MyPagerAdapter.setPrimaryItem (SecondActivity.java:80)
at android.support.v4.view.ViewPager.populate (ViewPager.java:1066)
at android.support.v4.view.ViewPager.populate (ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure (ViewPager.java:1436)
at android.view.View.measure (View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure (RelativeLayout.java:477)
at android.view.View.measure (View.java:15848)
at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:5012)
at com.android.internal.widget.ActionBarOverLayout.onMeasure(ActionBarOverLayout.java:302)
at android.view.View.measure (View.java:15848)
at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure (FrameLayout.java:310)
at android.view.View.measure (View.java:15848)
SecondActivity.java
package com.example.logger;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
public class SecondActivity extends Activity {
private static final int NUM_PAGES = 10;
private ViewPager mpager;
private MyPagerAdapter mPagerAdapter;
private int [] pics = {R.drawable.android_interfaz_layout_estructura_final, R.drawable.baixa, R.drawable.baixada, R.drawable.greenprogressbar,
R.drawable.layout_keyboard, R.drawable.linerlay, R.drawable.merge1, R.drawable.o2zds, R.drawable.regbd,
R.drawable.s7qrs};
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mPagerAdapter = new MyPagerAdapter(null);
mpager = (ViewPager) findViewById(R.id.viewer);
mpager.setAdapter (mPagerAdapter);
}
public void showImage (int position, View view)
{
//View is your view that you returned from instantiateItem
//and position is it's position in array you can get the image resource id
//using this position and set it to the ImageView
}
private class MyPagerAdapter extends PagerAdapter
{
SecondActivity activity;
public MyPagerAdapter (SecondActivity activity){
this.activity=activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView (SecondActivity.this);
view.setImageResource (pics[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void setPrimaryItem (ViewGroup container, int position, Object object)
{
super.setPrimaryItem (container, position, object);
activity.showImage(position,(View)object);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private OnClickListener mPageClickListener = new OnClickListener()
{
public void onClick (View v)
{
// TODO Auto-generated method stub
//aquí anirà la funció per traslladar la image de la gallery a la pantalla
Integer picId = (Integer) v.getTag();
mpager.setVisibility(View.VISIBLE);
mpager.setCurrentItem(v.getId());
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
};
}
End SecondActivity.java
Activity_Second.xml
<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=".SecondActivity" >
<android.support.v4.view.ViewPager
android:padding="16dp"
android:id="#+id/viewer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="0.30"
/>
<ImageView
android:id="#+id/big_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/viewer"
android:layout_weight="0.70"
/>
</RelativeLayout>
End Activity_Second.xml
Just in case I'll add the MainActivity as well.
Main_Activity.java
package com.example.logger;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
attachHandlers();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void attachHandlers() {
findViewById(R.id.login).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.login)
{
Intent i = new Intent(this, SecondActivity.class);
startActivity(i);
}
}
}
End MainActivity.java
Activity_Main.xml
<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"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Login"
android:layout_alignParentBottom="true"
android:background="#drawable/shapes"
android:textColor="#color/text"
/>
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/input_u"
android:layout_marginTop="10dp"
android:textColor="#color/text"
/>
<EditText
android:id="#+id/password"
android:layout_below="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/input_p"
android:layout_marginTop="10dp"
android:textColor="#color/text"
/>
</RelativeLayout>
End Activity_Main.xml
I'd be very grateful if I could receive some insight into how to fix these problems.
Yours sincerely,
Mauro.
Change this
mPagerAdapter = new MyPagerAdapter(null)
to
mPagerAdapter = new MyPagerAdapter(SecondActivity.this)
The constructor looks like
public MyPagerAdapter (SecondActivity activity){
this.activity=activity; //activity is null
}
Most likely line 80 in SecondActivity.java is activity.showImage(position,(View)object); and activity is null.
Change your Pageradapter code
class MyPagerAdapter extends PagerAdapter{
MyPagerAdapter (Context context) {
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public int getCount() {
return pics.length;
}
#Override
public Object instantiateItem(View collection, int position) {
ImageView iv = new ImageView(SecondActivity.this);
((ViewPager) collection).addView(iv, 0);
iv.setImageResource(pics[position]);
return iv;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
You are getting nullpointer error because of not getting the context of the activity in your MyPagerAdapter class
Change your initialization in your SecondActivity for the adapter as below:"
Instead of this
mPagerAdapter = new MyPagerAdapter(null);
Do this
mPagerAdapter = new MyPagerAdapter(SecondActivity.this)
it is working now
public class SecondActivity extends Activity {
private static final int NUM_PAGES = 10;
private ViewPager mpager;
private MyPagerAdapter mPagerAdapter;
private int[] pics = { R.drawable.flower1, R.drawable.flower10,
R.drawable.flower11, R.drawable.flower13, R.drawable.flower2,
R.drawable.flower6, R.drawable.flower8, R.drawable.flower7,
R.drawable.image3, R.drawable.flower3 };
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mPagerAdapter = new MyPagerAdapter(this,pics);
mpager = (ViewPager) findViewById(R.id.viewer);
mpager.setAdapter(mPagerAdapter);
}
public void showImage(int position, View view) {
// View is your view that you returned from instantiateItem
// and position is it's position in array you can get the image resource
// id
// using this position and set it to the ImageView
}
private class MyPagerAdapter extends PagerAdapter {
Activity activity;
int imageArray[];
public MyPagerAdapter(SecondActivity 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);
System.out.println(position);
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;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private OnClickListener mPageClickListener = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// aquí anirà la funció per traslladar la image de la gallery a la
// pantalla
Integer picId = (Integer) v.getTag();
mpager.setVisibility(View.VISIBLE);
mpager.setCurrentItem(v.getId());
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
};
}

android pager sliding tabstrip fragment changer

I want to change the layout by swyping over the tabs with fragments. Can anybody help me solve my problem?
Here is my fragmentactivity:
public class MainActivity extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
changeColor(currentColor);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment dialog = new QuickContactFragment();
dialog.show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeColor(int newColor) {
tabs.setIndicatorColor(newColor);
// change ActionBar color just if an ActionBar is available
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });
if (oldBackground == null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
ld.setCallback(drawableCallback);
} else {
getActionBar().setBackgroundDrawable(ld);
}
} else {
TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });
// workaround for broken ActionBarContainer drawable handling on
// pre-API 17 builds
// https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
td.setCallback(drawableCallback);
} else {
getActionBar().setBackgroundDrawable(td);
}
td.startTransition(200);
}
oldBackground = ld;
// http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowTitleEnabled(true);
}
currentColor = newColor;
}
public void onColorClicked(View v) {
int color = Color.parseColor(v.getTag().toString());
changeColor(color);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentColor", currentColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentColor = savedInstanceState.getInt("currentColor");
changeColor(currentColor);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
And here is my fragment that writes the numbers of the positions in a text view:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
.getDisplayMetrics());
TextView v = new TextView(getActivity());
params.setMargins(margin, margin, margin, margin);
v.setLayoutParams(params);
v.setLayoutParams(params);
v.setGravity(Gravity.CENTER);
v.setBackgroundResource(R.drawable.background_card);
v.setText("CARD " + (position + 1));
fl.addView(v);
return fl;
}
}
the library and the full code of the sample you can found here:
https://github.com/astuetz/PagerSlidingTabStrip
I know its late but might help someone:
Here is the quick fix:
Create other layouts first, let's assume that you create 3: I am also assuming the layout to give a clear idea
layout/lay1.xml - has a textview only
layout/lay2.xml - has an imageview only
layout/lay3.xml - has both textview and imageview
now inside oncreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// if else or switch case, your wish
View view;
if (position == 0) {
// means lay1.xml
view = inflater.inflate(R.layout.lay1, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText("Content not available");
return view;
} else if (position == 1) {
// means lay2.xml
view = inflater.inflate(R.layout.lay2, container, false);
ImageView imagebg = (ImageView) view.findViewById(R.id.image1);
imagebg.setImageResource(R.drawable.ic_launcher);
return view;
} else {
// means lay3.xml
view = inflater.inflate(R.layout.lay3, container, false);
ImageView imagebg = (ImageView) view.findViewById(R.id.image1);
imagebg.setImageResource(R.drawable.ic_launcher);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText("this is working wow, thanks.");
return view;
}
}

how do i use view pager with touchimageview

I am currently using TouchImageView to allow zooming in and out but now, I need also a View Pager using image view. How do I merge those two together? must I inflate the layout?
this is my viewpager
public class Main extends FragmentActivity implements AdapterView.OnItemSelectedListener, ViewPager.OnPageChangeListener{
private ViewPager viewPager;
String[] mImageIds;
private Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayImage();
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(this);
//gallery = (Gallery) findViewById(R.id.gallery);
//gallery.setAdapter(new ImageAdapter());
//gallery.setOnItemSelectedListener(this);
//textView = (TextView) findViewById(R.id.title);
handler = new Handler();
}
public void displayImage()
{
ArrayList<String> mStringList= new ArrayList<String>();
File strPath = new File(Environment.getExternalStorageDirectory() + "/Covers");
int lists = strPath.listFiles().length;
Log.d("number of items in array ",String.valueOf(lists));
File yourDir = new File(strPath, "");
for (File f : yourDir.listFiles()) {
if (f.isFile())
{
String name = f.getName();
String v = strPath + "/" + name;
mStringList.add(v);
}
}
mImageIds = new String[mStringList.size()];
mImageIds = mStringList.toArray(mImageIds);
for(int i = 0; i < mImageIds.length ; i++){
//Log.d("string is",(mImageIds[i]));
}
}
// gallery item selected
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
updateUI(i);
}
// view pager item selected
public void onPageSelected(int i) {
updateUI(i);
}
private void updateUI(final int i) {
handler.post(new Runnable() {
public void run() {
//gallery.setSelection(i);
viewPager.setCurrentItem(i);
///textView.setText("Photo #" + i);
}
});
}
public void onNothingSelected(AdapterView<?> adapterView) { }
public void onPageScrolled(int i, float v, int i1) { }
public void onPageScrollStateChanged(int i) { }
public class ImageAdapter extends BaseAdapter implements OnTouchListener {
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) {
ImageView imageView = new ImageView(Main.this);
imageView.setOnTouchListener(this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
public class EnableDisableViewPager extends ViewPager {
private boolean enabled = true;
public EnableDisableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if(enabled)
return super.onInterceptTouchEvent(arg0);
return false;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mImageIds.length;
}
#Override
public Fragment getItem(final int position) {
return new Fragment() {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = new ImageView(Main.this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
return imageView;
}
};
}
}
}
and its xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout android:layout_height="0px"
android:layout_width="fill_parent"
android:layout_weight="1"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip" />
</FrameLayout>
</LinearLayout>
Create an FragmentActivity whose layout consists of View Pager.
Add a Fragment foreach image whose layout consists of
TouchImageView.
Add these list of fragments to the View pager. Thats it. Pinch Zoom and pager both works.
Like this:
#Override
protected void onStart() {
super.onStart();
List<Fragment> fragments = new Vector<Fragment>();
String url1 = "someurl1.jpg";
Bundle Image1 = new Bundle();
Image1.putString("image_url", url1);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image1));
String url2 = "someurl2.jpg";
Bundle Image2 = new Bundle();
Image2.putString("image_url", url2);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image2));
//and so on.
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.animate();
mPager.setAdapter(this.mPagerAdapter);
}

Categories

Resources