hai i am doing one game here i need to display 100's of images into gallery,at the same time in wich image is in view that time i need to play that image related sound, i treid using sounpool for music play.i played sound correcltly but my prblem is in gallery scroling time when i move 1 image to 2 image that time both sounds 1 image,2 image related sounds are plying that time.how to solve that problem please any one suggest me..
Gallerynew .class:
public class Gallerynew extends Activity implements OnItemSelectedListener{
public boolean Visibility=true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoundManager.getInstance();
SoundManager.initSounds(this);
SoundManager.playSound(1, 1);
Gallery g=(Gallery)findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setSpacing(10);
g.setOnItemSelectedListener(this);
}
public class ImageAdapter extends BaseAdapter {
private Context myContext;
private int[] myImageIds = {
R.drawable.bokstavslottet01,
R.drawable.bokstavslottet02,
R.drawable.bokstavslottet03,
R.drawable.bokstavslottet04,
R.drawable.bokstavslottet05,
R.drawable.bokstavslottet06,
R.drawable.bokstavslottet07,
R.drawable.bokstavslottet08,
R.drawable.bokstavslottet09,
R.drawable.bokstavslottet10,
R.drawable.bokstavslottet11,
R.drawable.bokstavslottet12,
R.drawable.bokstavslottet13
};
public ImageAdapter(Context c) { this.myContext = c; }
public int getCount() {
// TODO Auto-generated method stub
return this.myImageIds.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView i = new ImageView(this.myContext);
i.setImageResource(this.myImageIds[position]);
/* Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.FIT_XY);
/* Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(700, 400));
Integer e = myImageIds.length;
Log.i("","length-------"+e);
return i;
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arg2==0){
SoundManager.playSound(1, 1);
}
if(arg2==1)
{
SoundManager.playSound(2, 1);
}
if(arg2==2)
{
SoundManager.playSound(3, 1);
}
if(arg2==3)
{
SoundManager.playSound(4, 1);
}
if(arg2==4)
{
SoundManager.playSound(5, 1);
}
if(arg2==5)
{
SoundManager.playSound(6, 1);
}
if(arg2==6)
{
SoundManager.playSound(7, 1);
}
if(arg2==7)
{
SoundManager.playSound(8, 1);
}
if(arg2==8)
{
SoundManager.playSound(9, 1);
}
if(arg2==9)
{
SoundManager.playSound(10, 1);
}
if(arg2==10)
{
SoundManager.playSound(11, 1);
}
if(arg2==11)
{
SoundManager.playSound(12, 1);
}
if(arg2==12)
{
SoundManager.playSound(13, 1);
}
}
#Override
public void onDestroy()
{
super.onDestroy();
SoundManager.cleanup();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
SoundManager .class:
public class SoundManager {
static private SoundManager _instance;
private static SoundPool mSoundPool;
private static HashMap<Integer, Integer> mSoundPoolMap;
private static AudioManager mAudioManager;
private static Context mContext;
private SoundManager()
{
}
/**
* Requests the instance of the Sound Manager and creates it
* if it does not exist.
*
* #return Returns the single instance of the SoundManager
*/
static synchronized public SoundManager getInstance()
{
if (_instance == null)
_instance = new SoundManager();
return _instance;
}
/**
* Initialises the storage for the sounds
*
* #param theContext The Application context
*/
public static void initSounds(Context theContext)
{
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
/**
* Add a new Sound to the SoundPool
*
* #param Index - The Sound Index for Retrieval
* #param SoundID - The Android ID for the Sound asset.
*/
public static void addSound(int Index,int SoundID)
{
mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
}
/**
* Loads the various sound assets
* Currently hardcoded but could easily be changed to be flexible.
*/
public static void loadSounds()
{
mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.starwars, 1));
mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.terminator, 1));
mSoundPoolMap.put(3, mSoundPool.load(mContext, R.raw.bokstavslottet_3, 1));
mSoundPoolMap.put(4, mSoundPool.load(mContext, R.raw.bokstavslottet_4, 1));
mSoundPoolMap.put(5, mSoundPool.load(mContext, R.raw.bokstavslottet_5, 1));
mSoundPoolMap.put(6, mSoundPool.load(mContext, R.raw.bokstavslottet_6, 1));
mSoundPoolMap.put(7, mSoundPool.load(mContext, R.raw.bokstavslottet_7, 1));
mSoundPoolMap.put(8, mSoundPool.load(mContext, R.raw.bokstavslottet_8, 1));
mSoundPoolMap.put(9, mSoundPool.load(mContext, R.raw.bokstavslottet_9, 1));
mSoundPoolMap.put(10, mSoundPool.load(mContext, R.raw.bokstavslottet_10, 1));
mSoundPoolMap.put(11, mSoundPool.load(mContext, R.raw.bokstavslottet_11, 1));
mSoundPoolMap.put(12, mSoundPool.load(mContext, R.raw.bokstavslottet_12, 1));
mSoundPoolMap.put(13, mSoundPool.load(mContext, R.raw.babycooing05, 1));
}
/**
* Plays a Sound
*
* #param index - The Index of the Sound to be played
* #param speed - The Speed to play not, not currently used but included for compatibility
*/
public static void playSound(int index,float speed)
{
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, speed);
}
/**
* Stop a Sound
* #param index - index of the sound to be stopped
*/
public static void stopSound(int index)
{
mSoundPool.stop(mSoundPoolMap.get(index));
}
public static void cleanup()
{
mSoundPool.release();
mSoundPool = null;
mSoundPoolMap.clear();
mAudioManager.unloadSoundEffects();
_instance = null;
}
}
i tried using mediaplyer its working good.but here each sound i need to set one mediaplyer object.in my app i need play some 100'of sounds.so is there any alternative solutoin please suggest me..
If you were using mediaplayer can could have easily stopped it using mp.isplaying() then do something.
But even i had the same issue i can suggest you one thing:
add a flag there and then you can check it the flag=true do something else do something
Ex: sound1 = mSoundPool.load(this, R.raw.abc, 1);
mSoundPool.play(sound1, 1, 1, 1, time - 1, 1);
loaded = true;
Now for the flag u can do like this
if(loaded == true)
{
mSoundPool.stop(sound1);
}
you can try this.
Related
I am new to Android AndEngine game development. I am developing a game in which i am using GenericPool to load multiple spites on the screen. Problem is that these sprites are of same type.I want to load different type of sprites. After some research i got the idea of using Multipool but do n't know how to use it in my code.
Here is my code :
public class Enemy {
public Sprite sprite;
public int hp;
// the max health for each enemy
protected final int MAX_HEALTH = 2;
Camera mCamera;
BaseActivity activity = BaseActivity.getSharedInstance();
public Enemy() {
sprite = new Sprite(32, 32, BaseActivity.getSharedInstance().mBirdTextureRegion,
BaseActivity.getSharedInstance().getVertexBufferObjectManager());
init();
}
// method for initializing the Enemy object , used by the constructor and
// the EnemyPool class
public void init() {
hp = MAX_HEALTH;
mCamera = activity.mCamera;
}
public void clean() {
sprite.clearEntityModifiers();
sprite.clearUpdateHandlers();
}
// method for applying hit and checking if enemy died or not
// returns false if enemy died
public boolean gotHit() {
synchronized (this) {
hp--;
if (hp <= 0)
return false;
else
return true;
}
}
public class EnemyLayer extends Entity {
private LinkedList<Enemy> enemies;
public static EnemyLayer instance;
public int enemyCount;
public static EnemyLayer getSharedInstance() {
return instance;
}
public static boolean isEmpty() {
if (instance.enemies.size() == 0)
return true;
return false;
}
public static Iterator<Enemy> getIterator() {
return instance.enemies.iterator();
}
public void purge() {
detachChildren();
for (Enemy e : enemies) {
EnemyPool.sharedEnemyPool().recyclePoolItem(e);
}
enemies.clear();
}
public EnemyLayer(int x) {
enemies = new LinkedList<Enemy>();
instance = this;
enemyCount = 4;
}
public void restart() {
Log.v("jimvaders", "EnemyLayer restarted");
enemies.clear();
clearEntityModifiers();
clearUpdateHandlers();
for (int i = 0; i < enemyCount; i++) {
Enemy e = EnemyPool.sharedEnemyPool().obtainPoolItem();
float finalPosX = (i % 6) * 2 * e.sprite.getWidth()/2 * 3/2;
float finalPosY = ((int) (i / 6)) * e.sprite.getHeight() * 2;
Random r = new Random();
e.sprite.setPosition(r.nextInt(2) == 0 ? -e.sprite.getWidth() * 3
: BaseActivity.CAMERA_WIDTH + e.sprite.getWidth() * 3,
(r.nextInt(5) + 1) * e.sprite.getHeight());
e.sprite.setVisible(true);
attachChild(e.sprite);
e.sprite.registerEntityModifier(new MoveModifier(1,
e.sprite.getX(), finalPosX, e.sprite.getY(), finalPosY));
enemies.add(e);
}
setVisible(true);
setPosition(50, 30);
MoveXModifier movRight = new MoveXModifier(1, 50, 120);
MoveXModifier movLeft = new MoveXModifier(1, 120, 50);
MoveYModifier moveDown = new MoveYModifier(1, 30, 100);
MoveYModifier moveUp = new MoveYModifier(1, 100, 30);
registerEntityModifier(new LoopEntityModifier(
new SequenceEntityModifier(movRight, moveDown, movLeft, moveUp)));
}
public static void purgeAndRestart() {
Log.v("Birds Shooter", "EnemyLayer PurgeAndRestart()");
instance.purge();
instance.restart();
}
#Override
public void onDetached() {
purge();
clearUpdateHandlers();
super.onDetached();
}
public class EnemyPool extends GenericPool<Enemy> {
public static EnemyPool instance;
public static EnemyPool sharedEnemyPool() {
if (instance == null)
instance = new EnemyPool();
return instance;
}
private EnemyPool() {
super();
}
#Override
protected Enemy onAllocatePoolItem() {
return new Enemy();
}
#Override
protected void onHandleObtainItem(Enemy pItem) {
pItem.init();
}
protected void onHandleRecycleItem(final Enemy e) {
e.sprite.setVisible(false);
e.sprite.detachSelf();
e.clean();
}
}
How can i modify this code to use multiple sprites of different types intead of same type.????? Any help will be appreciated .
You can extend the Sprite class and make new pools using the custom Sprite Object. For example:
public class FlyingEnemy extends Sprite
{
//Class Body Here
}
Once you have overwritten the Sprite class to match your needs you simply extend the generic pool to handle your new Sprites
public class FlyingEnemyPool extends GenericPool<FlyingEnemy>
{
//Class Body Here
}
Then you just use your new pools like normal.
I'm trying to implement Navigation Drawer using Drawer Layout without Action Bar.
Everything went smooth until i figured out that the drawer image didn't animate/slide like YouTube or Google Plus app.
What i meant with drawer image
Then i tried to implement my custom DrawerListener. Here is my activity class.
lstMenuDrawer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
selectMenu(pos);
}
});
drawerToggle = new GRHDrawerToggle(MainActivity.this, imvDrawer.getDrawable());
drawerLayout.setDrawerListener(drawerToggle);
And here is my listener class
public class GRHDrawerToggle implements DrawerListener {
private Activity mActivity;
private SlideDrawable mSlider;
/** Fraction of its total width by which to offset the toggle drawable. */
private static final float TOGGLE_DRAWABLE_OFFSET = 1 / 3f;
public GRHDrawerToggle(Activity activity, Drawable drawerImage){
mActivity = activity;
mSlider = new SlideDrawable(drawerImage);
mSlider.setOffset(TOGGLE_DRAWABLE_OFFSET);
}
#Override
public void onDrawerClosed(View arg0) {
// TODO Auto-generated method stub
mSlider.setPosition(0);
}
#Override
public void onDrawerOpened(View arg0) {
// TODO Auto-generated method stub
mSlider.setPosition(1);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// TODO Auto-generated method stub
float glyphOffset = mSlider.getPosition();
if (slideOffset > 0.5f) {
glyphOffset = Math.max(glyphOffset, Math.max(0.f, slideOffset - 0.5f) * 2);
} else {
glyphOffset = Math.min(glyphOffset, slideOffset * 2);
}
mSlider.setPosition(glyphOffset);
}
#Override
public void onDrawerStateChanged(int arg0) {
// TODO Auto-generated method stub
}
private class SlideDrawable extends InsetDrawable implements Drawable.Callback {
private final boolean mHasMirroring = Build.VERSION.SDK_INT > 18;
private final Rect mTmpRect = new Rect();
private float mPosition;
private float mOffset;
private SlideDrawable(Drawable wrapped) {
super(wrapped, 0);
}
/**
* Sets the current position along the offset.
*
* #param position a value between 0 and 1
*/
public void setPosition(float position) {
mPosition = position;
invalidateSelf();
}
public float getPosition() {
return mPosition;
}
/**
* Specifies the maximum offset when the position is at 1.
*
* #param offset maximum offset as a fraction of the drawable width,
* positive to shift left or negative to shift right.
* #see #setPosition(float)
*/
public void setOffset(float offset) {
mOffset = offset;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
copyBounds(mTmpRect);
canvas.save();
// Layout direction must be obtained from the activity.
final boolean isLayoutRTL = ViewCompat.getLayoutDirection(
mActivity.getWindow().getDecorView()) == ViewCompat.LAYOUT_DIRECTION_RTL;
final int flipRtl = isLayoutRTL ? -1 : 1;
final int width = mTmpRect.width();
canvas.translate(-mOffset * width * mPosition * flipRtl, 0);
// Force auto-mirroring if it's not supported by the platform.
if (isLayoutRTL && !mHasMirroring) {
canvas.translate(width, 0);
canvas.scale(-1, 1);
}
super.draw(canvas);
canvas.restore();
}
}
}
But still no sliding animation in my drawer button.
And then i realized method draw(Canvas canvas) in my listener class was never triggered.
Can someone tell me please where is my errors?
Many thanks.
gellaps
I am using pulltorefresh in my application.In onRefresh(), I tried to remove all the items by keeping listView.setAdapter(null);
But still my listView.getCount() is returning 1.
listView.setOnRefreshListener(new OnRefreshListener() {
// #Override
public void onRefresh() {
// Your code to refresh the list contents goes here
scroll=true;
pic.clear();
id.clear();
name.clear();
msg.clear();
img.clear();
profimg.clear();
objid.clear();
comment.clear();
weburl.clear();
adapter.clear();
likes.clear();
like_or_unlike.clear();
previousTotal = 0;
adapter.clear();
j=0;
loading = true;
webserv="https://graph.facebook.com/me/home?access_token="+accesstoken;
// listView.setAdapter(null);
System.out.println(listView.getCount());
// doInBack dob=new doInBack();
// dob.execute();
System.out.println(listView.getCount());
doback(webserv);
Log.e("hi","doback called");
}
});
My pulltorefresh class is
package com.beerbro.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.*;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.*;
import android.view.animation.Animation.AnimationListener;
import android.widget.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* A generic, customizable Android ListView implementation that has 'Pull to Refresh' functionality.
* <p/>
* This ListView can be used in place of the normal Android android.widget.ListView class.
* <p/>
* Users of this class should implement OnRefreshListener and call setOnRefreshListener(..)
* to get notified on refresh events. The using class should call onRefreshComplete() when
* refreshing is finished.
* <p/>
* The using class can call setRefreshing() to set the state explicitly to refreshing. This
* is useful when you want to show the spinner and 'Refreshing' text when the
* refresh was not triggered by 'Pull to Refresh', for example on start.
* <p/>
* For more information, visit the project page:
* https://github.com/erikwt/PullToRefresh-ListView
*
* #author Erik Wallentinsen <dev+ptr#erikw.eu>
* #version 1.0.0
*/
public class PullToRefreshListView extends ListView{
private static final float PULL_RESISTANCE = 1.7f;
private static final int BOUNCE_ANIMATION_DURATION = 700;
private static final int BOUNCE_ANIMATION_DELAY = 100;
private static final float BOUNCE_OVERSHOOT_TENSION = 1.4f;
private static final int ROTATE_ARROW_ANIMATION_DURATION = 250;
private static enum State{
PULL_TO_REFRESH,
RELEASE_TO_REFRESH,
REFRESHING
}
/**
* Interface to implement when you want to get notified of 'pull to refresh'
* events.
* Call setOnRefreshListener(..) to activate an OnRefreshListener.
*/
public interface OnRefreshListener{
/**
* Method to be called when a refresh is requested
*/
public void onRefresh();
}
private static int measuredHeaderHeight;
private boolean scrollbarEnabled;
private boolean bounceBackHeader;
private boolean lockScrollWhileRefreshing;
private boolean showLastUpdatedText;
private String pullToRefreshText;
private String releaseToRefreshText;
private String refreshingText;
private String lastUpdatedText;
private SimpleDateFormat lastUpdatedDateFormat = new SimpleDateFormat("dd/MM HH:mm");
private float previousY;
private int headerPadding;
private boolean hasResetHeader;
private long lastUpdated = -1;
private State state;
private LinearLayout headerContainer;
private RelativeLayout header;
private RotateAnimation flipAnimation;
private RotateAnimation reverseFlipAnimation;
private ImageView image;
private ProgressBar spinner;
private TextView text;
private TextView lastUpdatedTextView;
private OnItemClickListener onItemClickListener;
private OnItemLongClickListener onItemLongClickListener;
private OnRefreshListener onRefreshListener;
public PullToRefreshListView(Context context){
super(context);
init();
}
public PullToRefreshListView(Context context, AttributeSet attrs){
super(context, attrs);
init();
}
public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
init();
}
#Override
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
this.onItemClickListener = onItemClickListener;
}
#Override
public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener){
this.onItemLongClickListener = onItemLongClickListener;
}
/**
* Activate an OnRefreshListener to get notified on 'pull to refresh'
* events.
*
* #param onRefreshListener The OnRefreshListener to get notified
*/
public void setOnRefreshListener(OnRefreshListener onRefreshListener){
this.onRefreshListener = onRefreshListener;
}
/**
* #return If the list is in 'Refreshing' state
*/
public boolean isRefreshing(){
return state == State.REFRESHING;
}
/**
* Default is false. When lockScrollWhileRefreshing is set to true, the list
* cannot scroll when in 'refreshing' mode. It's 'locked' on refreshing.
*
* #param lockScrollWhileRefreshing
*/
public void setLockScrollWhileRefreshing(boolean lockScrollWhileRefreshing){
this.lockScrollWhileRefreshing = lockScrollWhileRefreshing;
}
/**
* Default is false. Show the last-updated date/time in the 'Pull ro Refresh'
* header. See 'setLastUpdatedDateFormat' to set the date/time formatting.
*
* #param showLastUpdatedText
*/
public void setShowLastUpdatedText(boolean showLastUpdatedText){
this.showLastUpdatedText = showLastUpdatedText;
if(!showLastUpdatedText) lastUpdatedTextView.setVisibility(View.GONE);
}
/**
* Default: "dd/MM HH:mm". Set the format in which the last-updated
* date/time is shown. Meaningless if 'showLastUpdatedText == false (default)'.
* See 'setShowLastUpdatedText'.
*
* #param lastUpdatedDateFormat
*/
public void setLastUpdatedDateFormat(SimpleDateFormat lastUpdatedDateFormat){
this.lastUpdatedDateFormat = lastUpdatedDateFormat;
}
/**
* Explicitly set the state to refreshing. This
* is useful when you want to show the spinner and 'Refreshing' text when
* the refresh was not triggered by 'pull to refresh', for example on start.
*/
public void setRefreshing(){
state = State.REFRESHING;
scrollTo(0, 0);
setUiRefreshing();
setHeaderPadding(0);
}
/**
* Set the state back to 'pull to refresh'. Call this method when refreshing
* the data is finished.
*/
public void onRefreshComplete(){
state = State.PULL_TO_REFRESH;
resetHeader();
lastUpdated = System.currentTimeMillis();
}
/**
* Change the label text on state 'Pull to Refresh'
*
* #param pullToRefreshText Text
*/
public void setTextPullToRefresh(String pullToRefreshText){
this.pullToRefreshText = pullToRefreshText;
if(state == State.PULL_TO_REFRESH){
text.setText(pullToRefreshText);
}
}
/**
* Change the label text on state 'Release to Refresh'
*
* #param releaseToRefreshText Text
*/
public void setTextReleaseToRefresh(String releaseToRefreshText){
this.releaseToRefreshText = releaseToRefreshText;
if(state == State.RELEASE_TO_REFRESH){
text.setText(releaseToRefreshText);
}
}
/**
* Change the label text on state 'Refreshing'
*
* #param refreshingText Text
*/
public void setTextRefreshing(String refreshingText){
this.refreshingText = refreshingText;
if(state == State.REFRESHING){
text.setText(refreshingText);
}
}
private void init(){
setVerticalFadingEdgeEnabled(false);
headerContainer = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.ptr_header, null);
header = (RelativeLayout) headerContainer.findViewById(R.id.ptr_id_header);
text = (TextView) header.findViewById(R.id.ptr_id_text);
lastUpdatedTextView = (TextView) header.findViewById(R.id.ptr_id_last_updated);
image = (ImageView) header.findViewById(R.id.ptr_id_image);
spinner = (ProgressBar) header.findViewById(R.id.ptr_id_spinner);
pullToRefreshText = getContext().getString(R.string.ptr_pull_to_refresh);
releaseToRefreshText = getContext().getString(R.string.ptr_release_to_refresh);
refreshingText = getContext().getString(R.string.ptr_refreshing);
lastUpdatedText = getContext().getString(R.string.ptr_last_updated);
flipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
flipAnimation.setInterpolator(new LinearInterpolator());
flipAnimation.setDuration(ROTATE_ARROW_ANIMATION_DURATION);
flipAnimation.setFillAfter(true);
reverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
reverseFlipAnimation.setInterpolator(new LinearInterpolator());
reverseFlipAnimation.setDuration(ROTATE_ARROW_ANIMATION_DURATION);
reverseFlipAnimation.setFillAfter(true);
addHeaderView(headerContainer);
setState(State.PULL_TO_REFRESH);
scrollbarEnabled = isVerticalScrollBarEnabled();
ViewTreeObserver vto = header.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new PTROnGlobalLayoutListener());
super.setOnItemClickListener(new PTROnItemClickListener());
super.setOnItemLongClickListener(new PTROnItemLongClickListener());
}
private void setHeaderPadding(int padding){
headerPadding = padding;
MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) header.getLayoutParams();
mlp.setMargins(0, Math.round(padding), 0, 0);
header.setLayoutParams(mlp);
}
#Override
public boolean onTouchEvent(MotionEvent event){
if(lockScrollWhileRefreshing
&& (state == State.REFRESHING || getAnimation() != null && !getAnimation().hasEnded())){
return true;
}
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
if(getFirstVisiblePosition() == 0) previousY = event.getY();
else previousY = -1;
break;
case MotionEvent.ACTION_UP:
if(previousY != -1 && (state == State.RELEASE_TO_REFRESH || getFirstVisiblePosition() == 0)){
switch(state){
case RELEASE_TO_REFRESH:
setState(State.REFRESHING);
bounceBackHeader();
break;
case PULL_TO_REFRESH:
resetHeader();
break;
}
}
break;
case MotionEvent.ACTION_MOVE:
if(previousY != -1){
float y = event.getY();
float diff = y - previousY;
if(diff > 0) diff /= PULL_RESISTANCE;
previousY = y;
int newHeaderPadding = Math.max(Math.round(headerPadding + diff), -header.getHeight());
if(newHeaderPadding != headerPadding && state != State.REFRESHING){
setHeaderPadding(newHeaderPadding);
if(state == State.PULL_TO_REFRESH && headerPadding > 0){
setState(State.RELEASE_TO_REFRESH);
image.clearAnimation();
image.startAnimation(flipAnimation);
}else if(state == State.RELEASE_TO_REFRESH && headerPadding < 0){
setState(State.PULL_TO_REFRESH);
image.clearAnimation();
image.startAnimation(reverseFlipAnimation);
}
return true;
}
}
break;
}
return super.onTouchEvent(event);
}
private void bounceBackHeader(){
int yTranslate = state == State.REFRESHING ?
header.getHeight() - headerContainer.getHeight() :
-headerContainer.getHeight() - headerContainer.getTop();
TranslateAnimation bounceAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0,
TranslateAnimation.ABSOLUTE, 0,
TranslateAnimation.ABSOLUTE, 0,
TranslateAnimation.ABSOLUTE, yTranslate);
bounceAnimation.setDuration(BOUNCE_ANIMATION_DURATION);
bounceAnimation.setFillEnabled(true);
bounceAnimation.setFillAfter(false);
bounceAnimation.setFillBefore(true);
bounceAnimation.setInterpolator(new OvershootInterpolator(BOUNCE_OVERSHOOT_TENSION));
bounceAnimation.setAnimationListener(new HeaderAnimationListener(yTranslate));
startAnimation(bounceAnimation);
}
private void resetHeader(){
if(getFirstVisiblePosition() > 0){
setHeaderPadding(-header.getHeight());
setState(State.PULL_TO_REFRESH);
return;
}
if(getAnimation() != null && !getAnimation().hasEnded()){
bounceBackHeader = true;
}else{
bounceBackHeader();
}
}
private void setUiRefreshing(){
spinner.setVisibility(View.VISIBLE);
image.clearAnimation();
image.setVisibility(View.INVISIBLE);
text.setText(refreshingText);
}
private void setState(State state){
this.state = state;
switch(state){
case PULL_TO_REFRESH:
spinner.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
text.setText(pullToRefreshText);
if(showLastUpdatedText && lastUpdated != -1){
lastUpdatedTextView.setVisibility(View.VISIBLE);
lastUpdatedTextView.setText(String.format(lastUpdatedText, lastUpdatedDateFormat.format(new Date(lastUpdated))));
}
break;
case RELEASE_TO_REFRESH:
spinner.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
text.setText(releaseToRefreshText);
break;
case REFRESHING:
setUiRefreshing();
lastUpdated = System.currentTimeMillis();
if(onRefreshListener == null){
setState(State.PULL_TO_REFRESH);
}else{
onRefreshListener.onRefresh();
}
break;
}
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt){
super.onScrollChanged(l, t, oldl, oldt);
if(!hasResetHeader){
if(measuredHeaderHeight > 0 && state != State.REFRESHING){
setHeaderPadding(-measuredHeaderHeight);
}
hasResetHeader = true;
}
}
private class HeaderAnimationListener implements AnimationListener{
private int height, translation;
private State stateAtAnimationStart;
public HeaderAnimationListener(int translation){
this.translation = translation;
}
public void onAnimationStart(Animation animation){
stateAtAnimationStart = state;
android.view.ViewGroup.LayoutParams lp = getLayoutParams();
height = lp.height;
lp.height = getHeight() - translation;
setLayoutParams(lp);
if(scrollbarEnabled){
setVerticalScrollBarEnabled(false);
}
}
// #Override
public void onAnimationEnd(Animation animation){
setHeaderPadding(stateAtAnimationStart == State.REFRESHING ? 0 : -measuredHeaderHeight - headerContainer.getTop());
setSelection(0);
android.view.ViewGroup.LayoutParams lp = getLayoutParams();
lp.height = height;
setLayoutParams(lp);
if(scrollbarEnabled){
setVerticalScrollBarEnabled(true);
}
if(bounceBackHeader){
bounceBackHeader = false;
postDelayed(new Runnable(){
// #Override
public void run(){
resetHeader();
}
}, BOUNCE_ANIMATION_DELAY);
}else if(stateAtAnimationStart != State.REFRESHING){
setState(State.PULL_TO_REFRESH);
}
}
// #Override
public void onAnimationRepeat(Animation animation){}
}
private class PTROnGlobalLayoutListener implements OnGlobalLayoutListener{
// #Override
public void onGlobalLayout(){
int initialHeaderHeight = header.getHeight();
if(initialHeaderHeight > 0){
measuredHeaderHeight = initialHeaderHeight;
if(measuredHeaderHeight > 0 && state != State.REFRESHING){
setHeaderPadding(-measuredHeaderHeight);
requestLayout();
}
}
getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
private class PTROnItemClickListener implements OnItemClickListener{
//
// #Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
hasResetHeader = false;
if(onItemClickListener != null && state == State.PULL_TO_REFRESH){
// Passing up onItemClick. Correct position with the number of header views
onItemClickListener.onItemClick(adapterView, view, position - getHeaderViewsCount(), id);
}
}
}
private class PTROnItemLongClickListener implements OnItemLongClickListener{
// #Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id){
hasResetHeader = false;
if(onItemLongClickListener != null && state == State.PULL_TO_REFRESH){
// Passing up onItemLongClick. Correct position with the number of header views
return onItemLongClickListener.onItemLongClick(adapterView, view, position - getHeaderViewsCount(), id);
}
return false;
}
}
}
I really didnt understand why it is returning 1 instead of 0.
Have you tried to clear the list and the notify the adapter?
I mean, If I use an String array to make the list:
ArrayList<String> names=new ArrayList<String>();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
If I want to clear it, I make:
names.clear();
adapter.notifyDataSetChanged();
I'm using this CoverFlow : http://www.inter-fuser.com/2010/02/android-coverflow-widget-v2.html
I want to for the coverflow to adapt to the different screen sizes,
I have modded the coverflow slightly so that I use an XML layout instead.
Here's how the layout should and looks like on my Phone (320x480)
Here's how the layout looks like on a Nexus One (480x720 in emulator)
COVERFLOW CLASS :
public class CoverFlow extends Gallery {
/**
* Graphics Camera used for transforming the matrix of ImageViews
*/
private final Camera mCamera = new Camera();
/**
* The maximum angle the Child ImageView will be rotated by
*/
private int mMaxRotationAngle = 80;
/**
* The maximum zoom on the centre Child
*/
// TODO RENDRE LA VALEUR DYNAMIQUE SUR LA TAILLE DE L'ECRAN
// private int mMaxZoom = -430;
private int mMaxZoom = -370;
/**
* The Centre of the Coverflow
*/
private int mCoveflowCenter;
public CoverFlow(Context context) {
super(context);
this.setStaticTransformationsEnabled(true);
}
public CoverFlow(Context context, AttributeSet attrs) {
super(context, attrs);
this.setStaticTransformationsEnabled(true);
}
public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setStaticTransformationsEnabled(true);
}
/**
* Get the max rotational angle of the image
* #return the mMaxRotationAngle
*/
public int getMaxRotationAngle() {
return mMaxRotationAngle;
}
/**
* Set the max rotational angle of each image
* #param maxRotationAngle the mMaxRotationAngle to set
*/
public void setMaxRotationAngle(int maxRotationAngle) {
mMaxRotationAngle = maxRotationAngle;
}
/**
* Get the Max zoom of the centre image
* #return the mMaxZoom
*/
public int getMaxZoom() {
return mMaxZoom;
}
/**
* Set the max zoom of the centre image
* #param maxZoom the mMaxZoom to set
*/
public void setMaxZoom(int maxZoom) {
mMaxZoom = maxZoom;
}
/**
* Get the Centre of the Coverflow
* #return The centre of this Coverflow.
*/
private int getCenterOfCoverflow() {
return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}
/**
* Get the Centre of the View
* #return The centre of the given view.
*/
private static int getCenterOfView(View view) {
return view.getLeft() + view.getWidth() / 2;
}
/**
* {#inheritDoc}
*
* #see #setStaticTransformationsEnabled(boolean)
*/
#Override
protected boolean getChildStaticTransformation(View child, Transformation t) {
final int childCenter = getCenterOfView(child);
final int childWidth = child.getWidth() ;
int rotationAngle = 0;
t.clear();
t.setTransformationType(Transformation.TYPE_MATRIX);
if (childCenter == mCoveflowCenter) {
transformImageBitmap((ImageView) child, t, 0);
} else {
rotationAngle = (int) (((float) (mCoveflowCenter - childCenter)/ childWidth) * mMaxRotationAngle);
if (Math.abs(rotationAngle) > mMaxRotationAngle) {
rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
}
transformImageBitmap((ImageView) child, t, rotationAngle);
}
return true;
}
/**
* This is called during layout when the size of this view has changed. If
* you were just added to the view hierarchy, you're called with the old
* values of 0.
*
* #param w Current width of this view.
* #param h Current height of this view.
* #param oldw Old width of this view.
* #param oldh Old height of this view.
*/
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCoveflowCenter = getCenterOfCoverflow();
super.onSizeChanged(w, h, oldw, oldh);
}
/**
* Transform the Image Bitmap by the Angle passed
*
* #param imageView ImageView the ImageView whose bitmap we want to rotate
* #param t transformation
* #param rotationAngle the Angle by which to rotate the Bitmap
*/
private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) {
mCamera.save();
final Matrix imageMatrix = t.getMatrix();;
final int imageHeight = child.getLayoutParams().height;;
final int imageWidth = child.getLayoutParams().width;
final int rotation = Math.abs(rotationAngle);
mCamera.translate(0.0f, 0.0f, 100.0f);
//As the angle of the view gets less, zoom in
if ( rotation < mMaxRotationAngle ) {
float zoomAmount = (mMaxZoom + rotation);
mCamera.translate(0.0f, 0.0f, zoomAmount);
}
mCamera.rotateY(rotationAngle);
mCamera.getMatrix(imageMatrix);
imageMatrix.preTranslate(-(imageWidth/2), -(imageHeight/2));
imageMatrix.postTranslate((imageWidth/2), (imageHeight/2));
mCamera.restore();
}
}
HOME ACTIVITY :
public class HomeActivity extends Activity {
private final static String TAG = "HomeActivity";
private TextView pageNameTextView;
private CoverFlow coverFlow;
private ImageAdapter coverImageAdapter;
private int itemSelected = 0;
private Context context;
private SparseArray<String> listeNomIcons;
private int currentImagePosition = 0;
//Info button
private ImageView infoAccueilImageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
//animate Transition
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
context = this;
listeNomIcons = new SparseArray<String>();
listeNomIcons.put(0, "DELAIS D'ATTENTE, RETARD");
listeNomIcons.put(1, "COURRIER SUBSTITUTION");
listeNomIcons.put(2, "IR LC");
listeNomIcons.put(3, "CONTACTS UTILES");
listeNomIcons.put(4, "TEMPS DE PAUSE");
listeNomIcons.put(5, "DISPERTION");
listeNomIcons.put(6, "PRORATA REPOS");
listeNomIcons.put(7, "ALERTE DOMICILE");
listeNomIcons.put(8, "RESERVE DOMICILE");
listeNomIcons.put(9, "RADD");
listeNomIcons.put(10, "JOKER");
coverFlow = (CoverFlow)findViewById(R.id.coverflow);
coverImageAdapter = new ImageAdapter(this);
coverFlow.setAdapter(coverImageAdapter);
coverFlow.setSelection(0, true);
coverFlow.setAnimationDuration(1000);
//cover
pageNameTextView = (TextView)findViewById(R.id.page_nameTextView);
//Info Accueil Image View
infoAccueilImageView = (ImageView)findViewById(R.id.infoImageView);
infoAccueilImageView.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(context, InfoAccueilActivity.class));
}
} ) ;
coverFlow.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
currentImagePosition = position; //this will update your current marker
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Button goLeft = (Button) findViewById(R.id.select_leftButton);
goLeft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// go to previous image
coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(0, 0));
}
});
Button goRight = (Button) findViewById(R.id.select_rightButton);
goRight.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// go to next item
coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));
}
});
coverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(itemSelected == arg2)
{
Log.d(TAG, "arg2 : "+arg2);
switch (arg2) {
case 0:
startActivity(new Intent(context, DelaisAttenteActivity.class));
break;
case 1:
startActivity(new Intent(context, CourrierSubstitutionActivity.class));
break;
case 2:
startActivity(new Intent(context, IRLCActivity.class));
break;
case 3:
startActivity(new Intent(context, ContactsActivity.class));
break;
case 4:
startActivity(new Intent(context, TempsPauseActivity.class));
break;
case 5:
startActivity(new Intent(context, DispertionActivity.class));
break;
case 6:
startActivity(new Intent(context, ProrataReposActivity.class));
break;
case 7:
startActivity(new Intent(context, AlerteDomicileActivity.class));
break;
case 8:
startActivity(new Intent(context, ReserveDomicileActivity.class));
break;
case 9:
startActivity(new Intent(context, ReposAdditionnelActivity.class));
break;
case 10:
startActivity(new Intent(context, JokerActivity.class));
break;
default:
break;
}
}
}
});
coverFlow.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
pageNameTextView.setText(listeNomIcons.get(arg2));
itemSelected = arg2;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private final Context mContext;
private final Integer[] mImageIds = {
R.drawable.retard_controller,
R.drawable.courrier_substitution_controller,
R.drawable.irmf_controller,
R.drawable.contacts_controller,
R.drawable.pause_controller,
R.drawable.dispersion_controller,
R.drawable.repos_controller,
R.drawable.alerte_controller,
R.drawable.reserve_domicile_controller,
R.drawable.repos_additionnel_controller,
R.drawable.joker_controller
};
private final ImageView[] mImages;
public ImageAdapter(Context c) {
mContext = c;
mImages = new ImageView[mImageIds.length];
}
#Override
public int getCount() {
return mImageIds.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Use this code if you want to load from resources
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new CoverFlow.LayoutParams(130, 130));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//Make sure we set anti-aliasing otherwise we get jaggies
BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
drawable.setAntiAlias(true);
return i;
//return mImages[position];
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}
I found a way around, not a great solution but it works pretty well on the devices that I have tested it on...
In the method (in the ImageAdapter in HomeActivity)
#Override
public View getView(int position, View convertView, ViewGroup parent)
there I change the size of the image on this line
i.setLayoutParams(new CoverFlow.LayoutParams(130, 130));
to
int imageSize = calculateSize();
i.setLayoutParams(new CoverFlow.LayoutParams(imageSize, imageSize));
I set imageSize in my onCreate with this method
public int calculateSize()
{
// GET SCREEN SIZE
Display display = getWindowManager().getDefaultDisplay();
// HEIGHT
int height = display.getHeight();
long roundedHeightSize = Math.round((0.2132*height)+27.177);
//WIDTH
int width = display.getWidth();
long roundedWidthSize = Math.round((0.4264*width)-6.9355);
return (int)((roundedHeightSize+roundedWidthSize)/2);
}
TO GET THE FUNCTION :
(0.2132*height)+27.177 & (0.4264*width)-6.9355
I tested manually the height of the image needed on the different devices I had available
Galaxy SIII : 300 (1280x720)
Xperia Mini Pro : 135 (480x320)
Xperia X10 Mini Pro : 95 (320x240)
f(1280)=300
f(480)=135
f(320)=95
f(x) = 0.2132X + 27.177
then I did the same as the width..
I then get the average of the height and width given from these two functions to get the best value for the height and width of the image (seeing as the image is square => width = height)
there is a alphaSpacing kind of int variable, just increase its value . however i can not not remember exact class and variable name as its almost 2 years, when i used this code . but yes, one thing i remember is that i came across very same issue and i had absolutely no idea about stackoverflow. so was trying with different values and eventually succeeded .
I suggested to use values from dimens.xml. As example in the getView method in the adapter:
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item_gallery, null);
((RelativeLayout) convertView.findViewById(R.id.image_issue_layout)).setLayoutParams(new CoverFlowView.LayoutParams(
app.getResources().getDimensionPixelSize(R.dimen.width_coverflow),
app.getResources().getDimensionPixelSize(R.dimen.height_coverflow)));
and in res folder specify different values width_coverflow for the different screens: values-sw600dp-land, values-sw720dp and so on...
I am using view pager indicator and i have sucessfully implemented it but My problem is that my swipe is very slow.Any help regarding this will be appreciated.
My indicator activity:
public class ViewPagerIndicatorActivity extends FragmentActivity {
static PagerAdapter mPagerAdapter;
static ViewPager mViewPager;
static ViewPagerIndicator mIndicator;
static int position,position1;
static String PositionTitle;
static String addposition;
ProgressDialog dialog;
public Context _context=this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create our custom adapter to supply pages to the viewpager.
try{
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
// Start at a custom position
RelativeLayout firsthead=(RelativeLayout)findViewById(R.id.firsthead);
firsthead.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ii=new Intent(getApplicationContext(),WebviewNew.class);
startActivity(ii);
}
});
mViewPager.setCurrentItem(0);
mIndicator = (ViewPagerIndicator)findViewById(R.id.indicator);
mViewPager.setOnPageChangeListener(mIndicator);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
mViewPager.setAdapter(null);
super.onDestroy();
}
class OnIndicatorClickListener implements ViewPagerIndicator.OnClickListener{
#Override
public void onCurrentClicked(View v) {
Toast.makeText(ViewPagerIndicatorActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onNextClicked(View v) {
mViewPager.setCurrentItem(Math.min(mPagerAdapter.getCount() - 1, mIndicator.getCurrentPosition() + 1));
}
#Override
public void onPreviousClicked(View v) {
mViewPager.setCurrentItem(Math.max(0, mIndicator.getCurrentPosition() - 1));
}
}
class PagerAdapter extends FragmentPagerAdapter implements ViewPagerIndicator.PageInfoProvider{
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
Fragment f = new Fragment();
if(pos==0)
{
f=LayoutOne.newInstance(_context);
}
if(pos==1)
{
f=LayoutTwo.newInstance(_context);
}
if(pos==2)
{
f=Layoutthree.newInstance(_context);
}
if(pos==3)
{
f=Layoutfour.newInstance(_context);
}
return f;
}
#Override
public int getCount() {
return list2.length;
}
#Override
public String getTitle(int pos){
PositionTitle=list2[pos];
return PositionTitle;
}
}
public static class ItemFragment extends ListFragment{
String[] l1;
static ItemFragment newInstance1(String[] date) {
ItemFragment f = new ItemFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putStringArray("date", date);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.l1=list2;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.date_fragment, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
public static final String[] list2 = new String[]{"Catagories","Latest","Most Downloaded","Top Rated"};
private class StartTaskP extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ViewPagerIndicatorActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String hello = null;
try
{} catch (Exception e)
{
e.printStackTrace();
}
return hello;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
mIndicator.init(0, mPagerAdapter.getCount(), mPagerAdapter);
Resources res = getResources();
System.out.println("test11");
Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
mIndicator.setFocusedTextColor(new int[]{78, 103, 0});
mIndicator.setUnfocusedTextColor(new int[]{255,255,255});
//mIndicator.setFocusedTextColor(R.drawable.navigationtextcurrent);
// Set images for previous and next arrows.
mIndicator.setArrows(prev, next);
mIndicator.setOnClickListener(new OnIndicatorClickListener());
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
dialog.dismiss();
}
}
and my ViewPagerIndicator:
public class ViewPagerIndicator extends RelativeLayout implements OnPageChangeListener {
private static final int PADDING = 10;
int i=0;
TextView mPrevious;
TextView mCurrent;
TextView mNext;
static int mCurItem;
int mRestoreCurItem = -1;
Intent ii= new Intent();
Context mContext;
static int PresentPosition1;
static String textCarrier;
LinearLayout mPreviousGroup;
LinearLayout mNextGroup;
int mArrowPadding;
int mSize;
ImageView mCurrentIndicator;
ImageView mPrevArrow;
ImageView mNextArrow;
static PageInfoProvider mPageInfoProvider;
int[] mFocusedTextColor;
int[] mUnfocusedTextColor;
OnClickListener mOnClickHandler;
public interface PageInfoProvider{
String getTitle(int pos);
}
public interface OnClickListener{
void onNextClicked(View v);
void onPreviousClicked(View v);
void onCurrentClicked(View v);
}
public void setOnClickListener(OnClickListener handler){
this.mOnClickHandler = handler;
mPreviousGroup.setOnClickListener(new OnPreviousClickedListener());
mCurrent.setOnClickListener(new OnCurrentClickedListener());
mNextGroup.setOnClickListener(new OnNextClickedListener());
}
public int getCurrentPosition(){
return mCurItem;
}
public void setPageInfoProvider(PageInfoProvider pageInfoProvider){
this.mPageInfoProvider = pageInfoProvider;
}
public void setFocusedTextColor(int[] col){
System.arraycopy(col, 0, mFocusedTextColor, 0, 3);
updateColor(0);
}
public void setUnfocusedTextColor(int[] col){
System.arraycopy(col, 0, mUnfocusedTextColor, 0, 3);
mNext.setTextColor(Color.argb(160, col[0], col[1], col[2]));
mPrevious.setTextColor(Color.argb(160, col[0], col[1], col[2]));
updateColor(0);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable state = super.onSaveInstanceState();
Bundle b = new Bundle();
b.putInt("current", this.mCurItem);
b.putParcelable("viewstate", state);
return b;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(((Bundle)state).getParcelable("viewstate"));
mCurItem = ((Bundle)state).getInt("current", mCurItem);
this.setText(mCurItem - 1);
this.updateArrows(mCurItem);
this.invalidate();
}
/**
* Initialization
*
* #param startPos The initially selected element in the ViewPager
* #param size Total amount of elements in the ViewPager
* #param pageInfoProvider Interface that returns page titles
*/
public void init(int startPos, int size, PageInfoProvider pageInfoProvider){
setPageInfoProvider(pageInfoProvider);
this.mSize = size;
setText(startPos - 1);
mCurItem = startPos;
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
addContent();
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
addContent();
}
public ViewPagerIndicator(Context context) {
super(context);
addContent();
}
/**
* Add drawables for arrows
*
* #param prev Left pointing arrow
* #param next Right pointing arrow
*/
public void setArrows(Drawable prev, Drawable next){
this.mPrevArrow = new ImageView(getContext());
//this.mPrevArrow.setImageDrawable(prev);
this.mPrevArrow.setVisibility(View.INVISIBLE);
this.mNextArrow = new ImageView(getContext());
//this.mNextArrow.setImageDrawable(next);
LinearLayout.LayoutParams arrowLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//arrowLayoutParams.gravity = Gravity.CENTER;
mPreviousGroup.removeAllViews();
mPreviousGroup.addView(mPrevArrow, arrowLayoutParams);
mPreviousGroup.addView(mPrevious, arrowLayoutParams);
mPrevious.setPadding(PADDING, 0, 0, 0);
mNext.setPadding(0, 0, PADDING, 0);
mArrowPadding = PADDING + prev.getIntrinsicWidth();
mNextGroup.addView(mNextArrow, arrowLayoutParams);
updateArrows(mCurItem);
}
/**
* Create all views, build the layout
*/
private void addContent(){
mFocusedTextColor = new int[]{244, 240, 211};
mUnfocusedTextColor = new int[]{160,131,21};
// Text views
// set font
mPrevious = new TextView(getContext());
mCurrent = new TextView(getContext());
mNext = new TextView(getContext());
RelativeLayout.LayoutParams previousParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
previousParams.addRule(RelativeLayout.ALIGN_LEFT);
previousParams.leftMargin=-28;
previousParams.topMargin=10;
RelativeLayout.LayoutParams currentParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
currentParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
currentParams.topMargin=10;
RelativeLayout.LayoutParams nextParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
nextParams.rightMargin=-40;
nextParams.topMargin=10;
// Groups holding text and arrows
mPreviousGroup = new LinearLayout(getContext());
mPreviousGroup.setOrientation(LinearLayout.HORIZONTAL);
mNextGroup = new LinearLayout(getContext());
mNextGroup.setOrientation(LinearLayout.HORIZONTAL);
mPreviousGroup.addView(mPrevious, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mNextGroup.addView(mNext, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mPreviousGroup, previousParams);
addView(mCurrent, currentParams);
addView(mNextGroup, nextParams);
mPrevious.setSingleLine();
mCurrent.setSingleLine();
mNext.setSingleLine();
mPrevious.setText("previous");
mCurrent.setText("current");
mNext.setText("next");
try{
Typeface tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/trebuc.otf");
mPrevious.setTypeface(tf);
mCurrent.setTypeface(tf);
mNext.setTypeface(tf);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
mPrevious.setClickable(false);
mNext.setClickable(false);
mCurrent.setClickable(true);
mPreviousGroup.setClickable(true);
mNextGroup.setClickable(true);
// Set colors
mNext.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
mPrevious.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
updateColor(0);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
positionOffsetPixels = adjustOffset(positionOffsetPixels);
position = updatePosition(position, positionOffsetPixels);
setText(position - 1);
/*System.out.println("PageScrolled:"+(position-1));
System.out.println("PageScrollednew:"+PresentPosition);
*/updateColor(positionOffsetPixels-1);
updateArrows(position);
//updatePositions(positionOffsetPixels);
updatePositions(position);
mCurItem = position;
Bundle ii=new Bundle();
//ii.putExtra("mcurItem", mCurItem);
ii.putInt("key", mCurItem);
}
void updatePositions(int positionOffsetPixels){
int textWidth = mCurrent.getWidth() - mCurrent.getPaddingLeft() - mCurrent.getPaddingRight();
int maxOffset = this.getWidth() / 2 - textWidth / 2 - mArrowPadding;
if(positionOffsetPixels > 0){
maxOffset %= this.getPaddingLeft();
int offset = Math.min(positionOffsetPixels, maxOffset);
mCurrent.setPadding(0, 0, 2 * offset, 0);
}else{
maxOffset -= this.getPaddingRight();
int offset = Math.max(positionOffsetPixels, -maxOffset);
mCurrent.setPadding(-2 * offset, 0, 0, 0);
}
}
void updateArrows(int position){
if(mPrevArrow != null){
mPrevArrow.setVisibility(position == 0 ? View.INVISIBLE : View.VISIBLE);
mNextArrow.setVisibility(position == mSize - 1 ? View.INVISIBLE : View.VISIBLE);
}
}
int updatePosition(int givenPosition, int offset){
int pos;
if(offset < 0){
pos = givenPosition + 1;
}else{
pos = givenPosition;
}
return pos;
}
/**
* Fade "currently showing" color depending on it's position
*
* #param offset
*/
void updateColor(int offset){
offset = Math.abs(offset);
// Initial condition: offset is always 0, this.getWidth is also 0! 0/0 = NaN
int width = this.getWidth();
float fraction = width == 0 ? 0 : offset / ((float)width / 4.0f);
fraction = Math.min(1, fraction);
int r = (int)(mUnfocusedTextColor[0] * fraction + mFocusedTextColor[0] * (1 - fraction));
int g = (int)(mUnfocusedTextColor[1] * fraction + mFocusedTextColor[1] * (1 - fraction));
int b = (int)(mUnfocusedTextColor[2] * fraction + mFocusedTextColor[2] * (1 - fraction));
mCurrent.setTextColor(Color.argb(255, r, g, b));
}
/**
* Update text depending on it's position
*
* #param prevPos
*/
void setText(int prevPos){
PresentPosition1=prevPos;
if(prevPos < 0){
mPrevious.setText("");
}else{
mPrevious.setText(mPageInfoProvider.getTitle(prevPos));
}
mCurrent.setText(mPageInfoProvider.getTitle(prevPos + 1));
PresentPosition1=prevPos;
//System.out.println("present text"+mPageInfoProvider.getTitle(prevPos + 1));
if(prevPos + 2 == this.mSize){
mNext.setText("");
}else{
mNext.setText(mPageInfoProvider.getTitle(prevPos + 2));
}
}
// Original:
// 244, 245, 0, 1, 2
// New:
// -2, -1, 0, 1, 2
int adjustOffset(int positionOffsetPixels){
// Move offset half width
positionOffsetPixels += this.getWidth() / 2;
// Clamp to width
positionOffsetPixels %= this.getWidth();
// Center around zero
positionOffsetPixels -= this.getWidth() / 2;
return positionOffsetPixels;
}
#Override
public void onPageSelected(int position) {
// Reset padding when the page is finally selected (May not be necessary)
mCurrent.setPadding(0, 0, 0, 0);
}
class OnPreviousClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onPreviousClicked(ViewPagerIndicator.this);
}
}
}
class OnCurrentClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onCurrentClicked(ViewPagerIndicator.this);
}
}
}
class OnNextClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onNextClicked(ViewPagerIndicator.this);
}
}
}
}