How to refer to activity element from viewpager - android

I try to write an app, that is using slide effect for activities and found that ViewPager from Compatibility Package is what I need. I successfully made the slide, it works in the way i want, but my problem is that I am not able to refer to the elements in my Activity.
This is my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.pager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
if (Fibonacci.getInstance().number != 0)
displayResults();
ImageButton btnCalculate = (ImageButton) findViewById(R.id.btnCalculateDark);
btnCalculate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// do button click
}
});
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 2;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.activity_dark;
break;
case 1:
resId = R.layout.activity_pale;
break;
}
View view = inflater.inflate(resId, null);
((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;
}
}
}
My problem is that I receive NullPointerEception for the following line:
ImageButton btnCalculate = (ImageButton) findViewById(R.id.btnCalculateDark);
I know it's because in setContentView I set up main.xml, and I want to refer to an element in activity_dark.xml or activity_pale.xml. Unfortunately i am not able to figure out how to refer to the element. Any hints would be appreciated! Thank you!

You should better use Fragments for this
http://developer.android.com/guide/components/fragments.html
but if you want do it like this, then try to set listener after page changed:
myPager.setOnPageChangeListener(new OnPageChangeListener(){
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
ImageButton btnCalculate = (ImageButton) findViewById(R.id.btnCalculateDark);
btnCalculate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// do button click
}
});
}
});

Related

How to implement a viewpager like below screen shot?

This is implemented in whatsapp,how to add a view(for audio) dynamically into the view pager like this.
i have implemented working example for images but how to do that when both image and audio files were there?
Any code or working example will be much appreciated.
Thank you in advance.
public class download_data_adapter extends PagerAdapter {
private Context context;
private List<Bitmap> data;
private List<String> path;
ImageButton btnplaypause;
private SeekBar seekBarProgress;
Button btnCancel;
private MediaPlayer mediaPlayer;
private PopupWindow pwindo;
private int mediaFileLengthInMilliseconds;
private final Handler handler = new Handler();
public download_data_adapter(Context c, List<Bitmap> b,List<String> s) {
context = c;
data = b;
path = s;
}
#Override
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(final ViewGroup container, int position) {
final TouchImageView imageView = new TouchImageView(context);
int padding = 5;
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageBitmap(data.get(position));
imageView.setTag(path.get(position));
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (imageView.getTag().toString().endsWith(".mp3")) {
initiatePopupWindow(imageView.getTag().toString());
}
}
private void initiatePopupWindow(final String tag) {
try {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.audio_play_layout,(ViewGroup) container. findViewById(R.id.rlAudioLayout));
pwindo = new PopupWindow(layout,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
pwindo.showAtLocation(layout, Gravity.CENTER,0, 0);
btnCancel = (Button) layout.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaPlayer.pause();
pwindo.dismiss();
}
});
seekBarProgress = (SeekBar) layout.findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99);
seekBarProgress.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v,
MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
* sb.getProgress();
mediaPlayer
.seekTo(playPositionInMillisecconds);
}
return false;
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer .setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(
MediaPlayer arg0,
int percent) {
seekBarProgress.setSecondaryProgress(percent);
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(
MediaPlayer arg0) {
btnplaypause
.setImageResource(R.drawable.button_play);
}
});
btnplaypause = (ImageButton) layout.findViewById(R.id.btnPlayPause);
btnplaypause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer
.setDataSource(tag);
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer
.getDuration();
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btnplaypause
.setImageResource(R.drawable.button_pause);
} else {
mediaPlayer.pause();
btnplaypause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer
.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Activity goes here:
in OnCreate i am calling async task to get the image/record's absolute paths from server,and adding those to list as of you are seeing "bitmaps" and "bitmapUrl" on post execute im adding the below code
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new download_data_adapter(context,bitmaps,bitmapUrl);
viewPager.setAdapter(adapter);
the main.xml can be
<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"
>
<RelativeLayout
android:id="#+id/wrapper1"
android:layout_width="match_parent"
android:layout_height="#dimen/titlebarsize"
android:background="#color/red">
<SeekBar
android:id="#+id/progressrecord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#drawable/violetborderbox"
android:thumb="#drawable/playbtn"
android:progressDrawable="#drawable/seekbar_progress"
android:paddingLeft="35dp"
android:paddingRight="35dp"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/wrapper2"
android:layout_below="#+id/wrapper1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/violetbg"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginBottom="200dp"
app:matchChildWidth="#+id/vg_cover"
/>
</RelativeLayout>
Create an xml with the following code
<?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:weightSum="2"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageone"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
/>
</LinearLayout>
and inflate this inside your adapter class
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
int[] flagone;
LayoutInflater inflater;
public ViewPagerAdapter(Context context,int[] flagsone) {
this.context = context;
this.flagone = flagsone;
}
#Override
public int getCount() {
return flag.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
ImageView imgone;
Button button;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_image, container,
false);
// Capture position and set to the TextViews
// Locate the ImageView in viewpager_item.xml
imgone = (ImageView) itemView.findViewById(R.id.imageone);
// Capture position and set to the ImageView
imgone.setImageResource(flagone[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
and in activity
onCreate(){
int imagelist1={R.drawable.image1};
int imagelist2={R.drawable.image2};
ViewPagerAdapter adapter = new ViewPagerAdapter(mContext, imagelist1,imaglist2);
// Binds the Adapter to the ViewPager
myViewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
//System.out.println("new page selected"+position);
pageposition=position;
}
#Override
public void onPageScrolled(int i, float v, int i2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
try{
imageview.setVisibility(View.GONE);
imagebutton.setVisibility(View.VISIBLE);
}
});
}

Limit area of screen for swipe gesture detection

I am using gesture detection to swipe between HUD views containing objects like seekbars overlaid on my app screen.
Is there a way to limit or set a portion of the screen to listen for detect gestures.
I am using a Custom ViewPager that looks like this.
main class.
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends Activity {
static GLSurfaceView mView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = (GLSurfaceView)findViewById(R.id.glview);
mView.setZOrderOnTop(false);
mView.setEGLContextClientVersion(2);
mView.setRenderer(new GLLayer(this));
mView.setDebugFlags(GLSurfaceView.DEBUG_CHECK_GL_ERROR);
mView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // use with mView.requestRender() for each user change
// Create and set adapter
CustomPagerAdapter adapter = new CustomPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.customviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
// Add page change listener to pager component
myPager.setOnPageChangeListener(new CustomPageChangeListener(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
customPageChangeListener
public class CustomPageChangeListener implements OnPageChangeListener, OnClickListener {
private Button buttonBlue = null;
private Button buttonYellow = null;
private Button buttonRed = null;
private ColorPicker colorPicker;
private Activity context = null;
/**
* Constructor
*/
public CustomPageChangeListener(Activity context) {
this.context = context;
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0 : {
buttonBlue = (Button) context.findViewById(R.id.buttonBlue);
buttonBlue.setOnClickListener(this);
colorPicker = (ColorPicker) context.findViewById(R.id.colorPicker1);
// other controls
break;
}
case 1 : {
buttonYellow = (Button) context.findViewById(R.id.buttonYellow);
buttonYellow.setOnClickListener(this);
//other controls
break;
}
case 2 : {
buttonRed = (Button) context.findViewById(R.id.buttonRed);
buttonRed.setOnClickListener(this);
// other controls
break;
}
}
}
and the adapter...
public class CustomPagerAdapter extends PagerAdapter {
public Object instantiateItem(final View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0: {
resId = R.layout.page_1;
break;
}
case 1: {
resId = R.layout.page_2;
break;
}
case 2: {
resId = R.layout.page_3;
break;
}
}
View view = inflater.inflate(resId, null);
((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 int getCount() {
return 3;
}
Many thanks.
First idea.
Try to watch your x and y value :
x = event.getX();
y = event.getY();
cut gestures on 100px on horisontaly:
if(x>100) return false;
else
return viewPager.onTouchEvent(event);

View's Visibity is getting set to GONE, but still View appears on the screen inside PagerAdapter

Please help me with this guys, i am stuck up
I am Working on a viewpager, where i require my linearlayout change it's visibilty on a button click, but the visibilty property seems to but not working.
Here is my code
public class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(final View collection, final int position) {
Log.d("Inside", "Pager");
PagerView = new View(collection.getContext());
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PagerView = inflater.inflate(R.layout.bigimage, null);
imgSubmenu = (ScalableImageView)PagerView.findViewById(R.id.imgSubMenu);
btnBack = (Button)PagerView.findViewById(R.id.btnBack);
btnCart = (Button) PagerView.findViewById(R.id.btnCart);
btnCallWaiter = (Button) PagerView.findViewById(R.id.btnCallWaiter);
btnPayBill = (Button) PagerView.findViewById(R.id.btnPayBill);
btnReadMore = (Button) PagerView.findViewById(R.id.btnReadMore);
btnAddtoOrder = (Button) PagerView.findViewById(R.id.btnAddtoOrder);
tvSubMenuName = (TextView) PagerView.findViewById(R.id.tvSubMenuName);
tvDescption = (TextView) PagerView.findViewById(R.id.tvDescrption);
readLayout=(LinearLayout)PagerView.findViewById(R.id.readLayout);
font = Typeface.createFromAsset(MenuSelectionActivity.this.getAssets(),
"fonts/BEBAS___.ttf");
btnBack.setTypeface(font, Typeface.BOLD);
btnCallWaiter.setTypeface(font, Typeface.BOLD);
btnPayBill.setTypeface(font, Typeface.BOLD);
btnReadMore.setTypeface(font, Typeface.BOLD);
tvSubMenuName.setTypeface(font, Typeface.BOLD);
btnReadMore.setTypeface(font, Typeface.BOLD);
tvDescption.setTypeface(font, Typeface.BOLD);
btnAddtoOrder.setTypeface(font, Typeface.BOLD);
((ViewPager) collection).addView(PagerView, 0);
DisplayItem(position);
btnReadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("readtype",""+readtype);
if(readtype==0)
{
readLayout.setVisibility(View.GONE);
btnReadMore.setText("READ MORE");
btnReadMore.setBackgroundResource(drawable.readmore);
readtype=1;
}
else
{
readLayout.setVisibility(View.VISIBLE);
btnReadMore.setText("READ LESS");
btnReadMore.setBackgroundResource(drawable.readless);
readtype=0;
}
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
return PagerView;
}
#Override
public void destroyItem(final View arg0, final int arg1,
final Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(final View arg0, final Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return SubMenuIdList.size();
}
}
Can anyone please help me up.
i think your code is right.
have you tried to set the visibility with int?
setVisibility(0) -> visible or setVisibility(View.VISIBLE)
setVisibility(4) -> invisible or setVisibility(View.INVISIBLE)
setVisibility(8) -> gone or setVisibility(View.GONE)

On Click listener is not working in View Pager

I am having two pages in ViewPager.In the two pages I am having buttons for which i have to make action on them.On click listener for button is working perfectly fine for second page and it is not working for first page.
Here is the activity and adapter class which i have tried
public class MainActivity extends Activity {
int noofsize = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this,
noofsize);
ViewPager myPager = (ViewPager) findViewById(R.id.reviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
And the adapter class is as follows
public class ViewPagerAdapter extends PagerAdapter implements OnClickListener {
int size;
Activity act;
View layout;
TextView pagenumber;
Button click;
public ViewPagerAdapter(MainActivity mainActivity, int noofsize) {
// TODO Auto-generated constructor stub
size = noofsize;
act = mainActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return size;
}
#Override
public Object instantiateItem(View container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.pages, null);
pagenumber = (TextView) layout.findViewById(R.id.pagenumber);
pagenumber.setText("Now your in Page"+position);
click = (Button) layout.findViewById(R.id.click);
click.setOnClickListener(this);
((ViewPager) container).addView(layout, 0);
return layout;
}
#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 void onClick(View v) {
// TODO Auto-generated method stub
if (v == click) {
Toast.makeText(act, "click event called", Toast.LENGTH_SHORT)
.show();
}
}
}
if you want to catch button click and do something, it is better to do it in simplest possible way...
less code is better!
here we go;
inside your layout.xml of the button component (or whatever is the component) should have this
android:onClick="onClick_function"
then you can automatically catch this event inside your code, all you need just have a function with the same name
public void onClick_function(View v) {
// here we go!
}
I Face this same problem,In my case it solved by set click listener in instantiateItem. You can do something like this may it can helpful
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
or
You Can try this also
click.setOnClickListener(act);
i think this part is wrong:
if (v == click) { // What is click ?! you can't compare that
Toast.makeText(act, "click event called", Toast.LENGTH_SHORT)
.show();
}
Replace it with:
if (v.getId() == R.id.theIdOfTheView) {
Toast.makeText(act, "click event called", Toast.LENGTH_SHORT)
.show();
}
Use this inside the instantiateItem:
container.onClickListener();

MediaPlayer button in my viewpager

I am building an app with a viewpager horizontal swipe. all of the pager components function however I cannot get my button to play. There are no errors with the code, it just doesnt work. thanks for you help.
package com.test.viewpager;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class viewpager extends Activity {
public MediaPlayer mp = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
OnClickListener listener = new OnClickListener(){
public void onClick(View v) {
if (mp == null) {
mp = MediaPlayer.create(viewpager.this, R.raw.song1);
mp.start();
}else {
mp.stop();
mp = null;
}
}};
if (btn != null)
btn.setOnClickListener(listener);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(2); }
public void farLeftButtonClick(View v) {
Toast.makeText(this, "Far Left Button Clicked", Toast.LENGTH_SHORT).show();
}
public void farRightButtonClick(View v) {
Toast.makeText(this, "Far Right Elephant Button Clicked", Toast.LENGTH_SHORT).show();
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5; }
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.page1;
break;
case 1:
resId = R.layout.page2;
break;
case 2:
resId = R.layout.page3;
break;
case 3:
resId = R.layout.page4;
break;
case 4:
resId = R.layout.page5;
break; }
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view; }
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2); }
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1); }
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null; }
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}}
}
Here is the 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" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myfivepanelpager"/>
</LinearLayout>
here is one of the panes page3.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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/newbutton"
android:layout_gravity= "center"
/>
I cannot get my button to play. There are no errors with the code, it
just doesnt work
That's because you're trying to inflate the button as part of the Activity's layout (main.xml). However, as you can already tell from the layouts you posted: that's not the case. The button is part of the 'page' that is displayed in the ViewPager; hence, move the button logic from the Activity's onCreate(...) to the PagerAdapter's instantiateItem(...).
That will yield something like this:
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// switch/case omitted for simplicity
View view = inflater.inflate(resId, null);
Button btn = (Button) findViewById(R.id.button1);
if (btn != null) btn.setOnClickListener(new View.new OnClickListener(){
#Override public void onClick(View v) {
if (mp == null) {
mp = MediaPlayer.create(viewpager.this, R.raw.song1);
mp.start();
} else {
mp.stop();
mp = null;
}
}
});
// add and return view etc.
}

Categories

Resources