Insert 3 images dynamically to horizontal scrollview or Viewpager - android

There is an image shown below for what I am looking for. Currently I am using view pager & circle indicator. In view page it is showing only a single image.
I want in one viewpager three images as shown in pic. When I slide that page, again three different images loaded form server with text below. How to do this? Any idea regarding this or any other way to achieve this?
My code is shown below.
I add some xml layout here: homespizzaview.xml
<LinearLayout
android:id="#+id/linearLayoutbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip" >
<android.support.v4.view.ViewPager
android:id="#+id/pagerMenu"
android:layout_width="0dip"
android:layout_height="100dip"
android:layout_weight="1"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">
</android.support.v4.view.ViewPager>
</LinearLayout>
<RelativeLayout
android:id="#+id/relativeLayoutDot1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip">
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicatorMenu"
android:layout_width="fill_parent"
android:layout_height="25dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:padding="10dip" />
</RelativeLayout>
HomeView .java
public class HomeView extends Activity {
adaptermenu = new MenuPagerAdapter();
pagerMenu = (ViewPager)findViewById(R.id.pagerMenu);
pagerMenu.setAdapter(adaptermenu);
pagerMenu.setCurrentItem(0);
pagerMenu.setOffscreenPageLimit(adapter.getCount());
pagerMenu.getAdapter().notifyDataSetChanged();
pagerMenu.setPageMargin(15);
indicator = (CirclePageIndicator)findViewById(R.id.indicatorMenu);
indicator.setViewPager(pagerMenu);
final float density1 = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density1);
indicator.setPageColor(0xFF000000);
indicator.setFillColor(0xFF888888);
indicator.setStrokeWidth(2 * density1);
//We set this on the indicator, NOT the pager
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// Toast.makeText(HomeSpizzaView.this, "Changed to page " + position, Toast.LENGTH_SHORT).show();
pagerMenu.setCurrentItem(position, false);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
indicator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pagerMenu.setCurrentItem(0);
Log.i("", "getCurrentItem"+ mPager.getCurrentItem());
pagerMenu.getAdapter().notifyDataSetChanged();
}
});
}
}
MenuPagerAdapter.java
public class MenuPagerAdapter extends PagerAdapter {
public int getCount() {
return 3;
}
public Object instantiateItem(View collection, int position) {
ImageView image = new ImageView(collection.getContext());
image.setPadding(20, 0, 20, 0);
int resId = 0;
switch (position) {
case 0:
resId = R.drawable.promotion1;
break;
case 1:
resId = R.drawable.promotion2;
break;
case 2:
resId = R.drawable.promotion3;
break;
}
image.setImageResource(resId);
((ViewPager) collection).addView(image, 0);
return image;
}
#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;
}
}
here is update code which is showing single image view with below textview. i am looking for dynamic image & text.. means In 1 view pager 3 images with 3 text.. currently its showing 1 image view with below text.. I am looking for 3 images in single viewpager.. if i add linear layout it shows 3 image. but i add relative layout its showing single images.. ANY IDEA WHAT I MADE MISTIKE.
public Object instantiateItem(View collection, int position) {
RelativeLayout lLayout;
RelativeLayout.LayoutParams relativeLayout;
lLayout = new RelativeLayout (collection.getContext());
relativeLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
for (int i = 0; i < 3; i++) {
image = new ImageView(collection.getContext());
image.setPadding(20, 0, 20, 0);
image.setId(1);
int res = 0;
switch (0) {
case 0:
res = R.drawable.menu_antipasti;
break;
case 1:
res = R.drawable.menu_combos;
break;
case 2:
res = R.drawable.menu_drinks;
break;
}
image.setImageResource(res);
lLayout.addView(image);
textview = new TextView(collection.getContext());
textview.setTextColor(Color.BLACK);
textview.setId(2);
textview.setText("pizza");
textview.setPadding(60, 0, 20, 0);
relativeLayout.addRule(RelativeLayout.BELOW, image.getId());
lLayout.addView(textview, relativeLayout);
}
((ViewPager) collection).addView(lLayout, 0);
return lLayout;
}

Now you're returning ImageView from instantiateItem method. If you want to have 3 images on 1 page you need to create layout, place 3 images on it and return it. E.g:
public Object instantiateItem(View collection, int position) {
LinearLayour images = new LinearLayout(collection.getContext());
for (int i = 0; i < 3; i++) {
ImageView image = new ImageView(collection.getContext());
image.setPadding(20, 0, 20, 0);
images.addView(image);
int res = someResource depending on i and position.
image.setImageResource(res);
}
((ViewPager) collection).addView(images, 0);
return images;
}

Related

View Pager Issue in Android

I m using a viewpager which is rendering fragments one after the other. The problem which I m facing is that once I touch the current fragment visible,it takes the touch event of the next fragment which is yet to be loaded. How should I make sure the current/visible fragment is touched & the touch event is handled accordingly.
This is my adapter which renders the fragments.
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d("zambob",position+":"+slideShowItems.get(position).name);
Fragment fragment = new ScreenSlidePageFragment();
Bundle bundle = new Bundle();
bundle.putString("IMAGE_URL",slideShowItems.get(position).image);
bundle.putString("CAPTION", slideShowItems.get(position).name);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return slideShowItems.size();
}
}
This is the Fragment Class which handles the touch event as well.
public class ScreenSlidePageFragment extends Fragment {
String imageUrl,text;
UWSharedPreference preference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_slide_show, container, false);
rootView.getBackground().setAlpha(200);
preference = new UWSharedPreference(getActivity());
imageUrl = getArguments().getString("IMAGE_URL");
text = getArguments().getString("CAPTION");
TouchImageView iv_image = (TouchImageView) rootView.findViewById(R.id.jj_image);
TextView tv_caption = (TextView) rootView.findViewById(R.id.caption_text);
iv_image.setImageUrl(imageUrl, AppController.getInstance().getImageLoader());
if (text != null && text.equals("custom")){
tv_caption.setText("");
}
else {
tv_caption.setText(text);
}
iv_image.setOnTouchListener(new OnTouchListener());
return rootView;
}
class OnTouchListener implements View.OnTouchListener {
public boolean onTouch(View v, MotionEvent event) {
Log.d("zambob","On Touch Called for text" + text +" diner txn id" + preference.getDinerTxnID());
if (text.equals("custom") && preference.getDinerTxnID()!=0 ){
startActivity(new Intent(getActivity(), FBCheckInActivity.class));
getActivity().finish();
}
else {
getActivity().onBackPressed();
}
return true;
}
}
}
Now the problem is that in view pager, 3 fragments are loaded initially. The one visible, one behind it & the one which will come next. When i touch the fragment which is required to start the intent process doesn't work. But when i touch the fragment before the above one, then the required process is going on .
How should i make sure that when i touch the visible fragment, then the required process starts?
Finally I found the solution myself & a little help from Google as well :P.
Actually i was using Depth Page Transformer to show the swipe movements between the fragments. So i just tweaked the page transformer by using this-:
mPager.setPageTransformer(true, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
float translationX;
float scale;
float alpha;
if (position >= 1 || position <= -1) {
// Fix for https://code.google.com/p/android/issues/detail?id=58918
translationX = 0;
scale = 1;
alpha = 1;
} else if (position >= 0) {
translationX = -page.getWidth() * position;
scale = -0.2f * position + 1;
alpha = Math.max(1 - position, 0);
} else {
translationX = 0.5f * page.getWidth() * position;
scale = 1.0f;
alpha = Math.max(0.1f * position + 1, 0);
}
mPager.setTranslationX(translationX);
mPager.setScaleX(scale);
mPager.setScaleY(scale);
mPager.setAlpha(alpha);
}
});
This simply makes sure the visible fragment is getting touched and not the one behind the visible fragment by setting the scale, alpha & translation of the View Pager. Also make the root layout of View Pager as clickable.
XML for the activity rendering the View Pager.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:urbanwand="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:clickable="true"
tools:context="com.urbanwand.diner.SlideShowActivity">
<com.urbanwand.MyViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
urbanwand:scrollduration="500"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Hope this answer helps !

Page curl not working in Action bar tabs

I am referred the Harism page curl to implement it in Action bar
tabs.Because I thought this is the only thing should fulfill my requirement.
Below I am showing the output what I get it till now.
I need to add the pager curl in Viewpager.So that the action bar tabs
will swipe along with curl page.
Below I am posted the codes related to that.
MainActivity.java:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private CurlView mCurlView;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
#SuppressWarnings("unused")
private Menu optionsMenu;
private MenuItem menuItem;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
mCurlView.setBackgroundColor(0xFF202830);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object getLastCustomNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.layout.fragment_top_rated, R.layout.fragment_games,
R.layout.fragment_movies };
#Override
public int getPageCount() {
return 2;
}
private Bitmap loadBitmap(int width, int height, int index) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("index", String.valueOf(index));
View v = inflater.inflate(mBitmapIds[index], null);
v.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
default:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
// mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<info.androidhive.tabsswipe.adapter.CurlView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/curl"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</info.androidhive.tabsswipe.adapter.CurlView>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
TopRatedFragment.java:
public class TopRatedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
fragment_top_rated.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fa6a6a"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="Design Top Rated Screen"
android:textSize="20dp" />
</RelativeLayout>
TabsPagerAdapter.java:
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
My issue is I need to add the page curl in ViewPager.So that I can do the swipe along with viewpager.I didn't know how to do that.But I am trying to get it.Any suggestion is mostly appreciated.Thank you.
ActionBar tabs are deprecated in 5.0
Perhaps a page transform that doesn't break for use with a viewpager.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mPager.setPageTransformer(true, new DepthPageTransformer());
}
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final String TAG="DepthTransformer";
private static float MIN_SCALE = 0.75f;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
Log.d(TAG, "VIew " + view + " Position: " + position);
if (position <= -1) { // [-Infinity,-1) ] ***
// RLP> I Changed to include "-1" as well: When position is -1, the view is not visible
// This page is way off-screen to the left.
view.setAlpha(0);
Log.d(TAG, "VIew "+view+" Position: "+position+", way left");
view.setVisibility(View.GONE);
} else if (position <= 0) { // [ (-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
if (position==0) {
Log.d(TAG, "View "+view+" focused now?");
}
if (view.getVisibility()!=View.VISIBLE)
view.setVisibility(View.VISIBLE);
} else if (position <= 1) { // (0,1]
// Fade the page out.
view.setAlpha(1 - position);
// Counteract the default slide transition
// I THINK THIS IS WHAT BREAKS EVERYTHING
// ViewPager normally has the views one after another, but this makes all views on top
view.setTranslationX(pageWidth * -position);
// Scale the page down (between MIN_SCALE and 1)
float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
if (position==1) {
Log.d(TAG, "View "+view+" invisible now?");
view.setVisibility(View.GONE);
// we totally hide the view. This seems to solve focus issue
} else {
if (view.getVisibility()!=View.VISIBLE)
view.setVisibility(View.VISIBLE);
}
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
// we totally hide the view. This seems to solve focus issue
// I have to check for strange side-effects, but so far I found none :)
view.setVisibility(View.GONE);
Log.d(TAG, "VIew "+view+" Position: "+position+", way right");
}
}
}
Harism's page curl is designed for bitmaps, not for views. With that module, it is not possible to reach what you want, unless your tab contains only bitmaps

Android: first element of a GridView is misplaced in galaxy S3 and S4

I'm building an app that has a mini slotMachine game inside. The problem is that I use a GridView for each column of the slot and for some devices (not all) the first symbol of the slot has a space above that comes from nowhere...
The table of the slot is 3 rows X 5 columns.
The space doesn't come from the calculation of the symbol width and height because I've found that with two devices withe perfectly identical resolution and density (Galaxy tab 10.1 and Galaxy note 10.1) the spacing is different: 0 for one and 5 for the other.
Any help?
My MainActivity:
public class MainActivity extends Activity{
SlotView slot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slot=new SlotView(this);
slot.refreshSlotView("AAAAAAAAAAAAAAA");
}
}
SlotView:
public class SlotView {
private ArrayList<GridAdapter> adapter=new ArrayList<GridAdapter>();
public float H_RATIO=2/3; //height ratio of the grid based on the device
public float W_RATIO=5/6; //width ratio of the grid based on the device
Activity activity;
String path = "file:///android_asset/Slot/Slot-";
public SlotView(Context c){
activity = (Activity) c;
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
final int hDisplay=dm.heightPixels;
int wImage=(1024*hDisplay)/768; //width of the central image
float heightGrid=(hDisplay*2)/3; //grid height
float widthGrid=((wImage*5)/6); //grid width
float heightSymbol=(heightGrid-(8))/3; // symbol height (3 symbols for column with a spacing of 4 px)
//relative layout for the container table
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams((int)widthGrid, (int)heightGrid);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
// grid of the slot
LinearLayout grid_layout=(LinearLayout)activity.findViewById(R.id.layout_grid);
grid_layout.setLayoutParams(params);
grid_layout.setGravity(Gravity.TOP);
// gridview of the columns
LinearLayout.LayoutParams params_grid=new LinearLayout.LayoutParams((int)heightSymbol, (int)heightGrid);
for(int i=0; i<5; i++){ // five columns
GridView slot=new GridView(activity);
slot.setScrollContainer(false);
slot.setVerticalScrollBarEnabled(false);
slot.setHorizontalScrollBarEnabled(false);
if(i<4) {
params_grid.setMargins(0,0,4,0); // spacing between each column
}
slot.setLayoutParams(params_grid);
slot.setVerticalSpacing(4);
slot.setPadding(0, 0, 0, 0);
slot.setColumnWidth((int)heightSymbol);
slot.setNumColumns(GridView.AUTO_FIT);
slot.setGravity(Gravity.CENTER);
GridAdapter grid_adapter=new GridAdapter(activity, (int)heightSymbol, (int)heightSymbol);
adapter.add(grid_adapter);
slot.setAdapter(grid_adapter);
grid_layout.addView(slot);
}
}
public void refreshSlotView(String configTris){
for(int pos=0; pos<5; pos++){
String[] mThumbIds=new String[3];
int z=0;
for(int i=pos; z<3 && i<configTris.length(); i=i+5){
char letter=configTris.charAt(i);
mThumbIds[z]=path + letter + ".png";
z++;
}
adapter.get(pos).setArrayOfImage(mThumbIds);
adapter.get(pos).notifyDataSetChanged();
}
}
}
The adapter:
public class GridAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds={};
private int w;
private int h;
public GridAdapter(Context c, int w, int h) {
mContext = c;
this.w=w;
this.h=h;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
ImageView imageView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.slot_element, null);
RelativeLayout rel=(RelativeLayout)view.findViewById(R.id.rel);
rel.setLayoutParams(new GridView.LayoutParams(w, h));
imageView=(ImageView)view.findViewById(R.id.image);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(w, h);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(params);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}else{
imageView = (ImageView) view.findViewById(R.id.image);
}
Picasso.with(mContext).load(mThumbIds[position]).into(imageView); // puts the image in the imageview
return view;
}
public void setArrayOfImage(String[] images){
this.mThumbIds=images;
}
public void showSymbolAtIndex(char letter, int position){
mThumbIds[position]="file:///android_asset/" + "Slot/Slot-" + letter + ".png";
notifyDataSetChanged();
}
}
This is the MainActivity Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/layout_grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
And the slot_element Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rel"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
</RelativeLayout>
Now that's the result:
And that's the proof of the existing spacing (if I drag one of the columns up):

Can't create a View Pager

I want to create a ViewPager, but when I execute the application in my phone, it shows me a blank activity and then the following error message:
The application testViewPager (process com.example.testviewpager) has stopped unexpectedly. Please try again.
How can I go about fixing this problem?
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<com.example.testviewpager.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.testviewpager.PagerContainer>
</RelativeLayout>
PagerActivity.java:
public class PagerActivity extends Activity {
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pager.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove
// clipping on the pager for its children.
pager.setClipChildren(false);
}
//Nothing special about this adapter, just throwing up colored views for demo
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
}
PagerContainer.java:
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
MainActivity.java:
public class MainActivity extends Activity
{
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
// Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
// A little space between pages
pager.setPageMargin(15);
}
// Nothing special about this adapter, just throwing up colored views for
// demo
private class MyPagerAdapter extends PagerAdapter
{
#Override
public Object instantiateItem(ViewGroup container, int position)
{
TextView view = new TextView(MainActivity.this);
view.setText("Item " + position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50,
position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);
}
#Override
public int getCount()
{
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return (view == object);
}
}
}

How to do Horizontal scroll view with images scroll in two directions

I am trying to show horizontal scroll view with images to scroll in two directions.Previously for this i used Gallery View but galleryview is deprected ,i am using horizontal scroll view instead of gallery view but horizontal scroll view is different with gallery view.
Now i have to do two implementation
1) Scrolling in two directions continuously.
2) Center lock feature as same as gallery.
My screen looks like
you can use viewpager,
try this code and modify it as your need .
note : this not my code already found it on the net belong to:
( Dave Smith,#devunwired Date: 8/17/12 PagerActivity).
MainActivity:
public class MainActivity extends Activity{
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
// Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
// A little space between pages
pager.setPageMargin(15);}
// Nothing special about this adapter, just throwing up colored views for
// demo
private class MyPagerAdapter extends PagerAdapter{
#Override
public Object instantiateItem(ViewGroup container, int position){
TextView view = new TextView(MainActivity.this);
view.setText("Item " + position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50,
position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);}
#Override
public int getCount(){
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return (view == object);
}}}
PagerContainer:
public class PagerContainer extends FrameLayout implements
ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a
ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y -
mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
public void onPageSelected(int position) { }
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.testviewpager.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC" >
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.testviewpager.PagerContainer>
</RelativeLayout>
hope help you.

Categories

Resources