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);
}
});
}
Related
I am currently working with Android and UltimateRecycleView. I manage to make the ultimaterecycleview working, but when I tried to use the load more functionality, the bottom progress bar is not showing (although the data is loaded). Anyone has experienced this problem? Can you please help me to find out what is wrong?
Here is the code :
--- Adapter ---
public class ListPendingAdapter extends UltimateViewAdapter<ListPendingAdapter.PendingViewHolder> {
private Context context;
private List<Queue> queues;
public ListPendingAdapter(Context context, List<Queue> queues) {
this.context = context;
this.queues = queues;
}
#Override
public PendingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.pending_list, parent, false);
PendingViewHolder vh = new PendingViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(PendingViewHolder holder, int position) {
TextView nodata = (TextView) ((Activity) context).findViewById(R.id.nodata);
if(queues.size() <= 0){
nodata.setVisibility(View.VISIBLE);
} else {
nodata.setVisibility(View.GONE);
User user = new User(queues.get(position).getQueuer());
if (user.getProfilePicture() == null) {
holder.photo.setImageDrawable(context.getResources().getDrawable(R.drawable.default_photo));
} else {
ImageUtil.setParseFileImageToView(context, user.getProfilePicture(), holder.photo);
}
holder.name.setText(user.getFullname());
holder.totalPerson.setText(Integer.toString(queues.get(position).getTotalPax()));
holder.timeQueue.setText(DateUtil.formatDateIntoTimeString(queues.get(position).getCreatedAt()));
attachButtonClickListener(holder.accept, true, position, holder.parent);
attachButtonClickListener(holder.reject, false, position, holder.parent);
CustomerUtil.attachUsernameListener((Activity) context, holder.name, queues.get(position));
CustomerUtil.attachProfpicListener((Activity) context, holder.photo, queues.get(position));
}
}
#Override
public int getItemCount() {
int size = (queues == null ? 0 : queues.size());
return size;
}
#Override
public PendingViewHolder onCreateViewHolder(ViewGroup viewGroup) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.pending_list, viewGroup, false);
PendingViewHolder vh = new PendingViewHolder(v);
return vh;
}
#Override
public PendingViewHolder getViewHolder(View view) {
return new PendingViewHolder(view);
}
#Override
public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.custom_bottom_progressbar, viewGroup, false);
return new RecyclerView.ViewHolder(view) {
};
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
}
#Override
public long generateHeaderId(int position) {
if (getItem(position).get("objectId").toString().length() > 0)
return (getItem(position).get("objectId").toString()).charAt(0);
else return -1;
}
#Override
public int getAdapterItemCount() {
int size = (queues == null ? 0 : queues.size());
return size;
}
public Queue getItem(int position) {
if (customHeaderView != null)
position--;
if (position < queues.size())
return queues.get(position);
else return null;
}
private void attachButtonClickListener(Button button, final boolean isAccept, final int position, final View parent){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPendingProcess(isAccept, position, parent);
}
});
}
private void callPendingProcess(final boolean isAccept, final int position, final View parent){
ProcessPending processPending = new ProcessPending(context, this, isAccept, position, parent);
processPending.execute();
}
public List<Queue> getDataset(){
return queues;
}
public static class PendingViewHolder extends UltimateRecyclerviewViewHolder {
public CircleImageView photo;
public TextView name;
public TextView totalPerson;
public TextView timeQueue;
public Button accept;
public Button reject;
public View parent;
public PendingViewHolder(View v) {
super(v);
parent = v;
photo = (CircleImageView) v.findViewById(R.id.photo);
name = (TextView) v.findViewById(R.id.cust_name);
totalPerson = (TextView) v.findViewById(R.id.total_cust);
timeQueue = (TextView) v.findViewById(R.id.time_queue);
accept = (Button) v.findViewById(R.id.accept_btn);
reject = (Button) v.findViewById(R.id.reject_btn);
}
}
}
--- Async Task (where I set the adapter to listview) ---
public class LoadPendingCustomer extends AsyncTask<Void, Void, List<Queue>> {
private Context context;
private Activity activity;
private ProgressBar pb;
private View view;
private View layout;
private int skipCount;
private boolean isLoadMore;
public LoadPendingCustomer(Context context, View layout, int skipCount, boolean isLoadMore) {
this.context = context;
this.activity = (Activity) context;
this.layout = layout;
this.skipCount = skipCount;
this.isLoadMore = isLoadMore;
this.pb = (ProgressBar) layout.findViewById(R.id.pending_progress);
this.view = layout.findViewById(R.id.pending_list_container);
}
#Override
protected void onPreExecute() {
if(!isLoadMore) {
ProgressUtil.showProgress(true, view, pb, context);
}
}
#Override
protected List<Queue> doInBackground(Void... arg0) {
List<Queue> queues = null;
try {
List<String> statuses = new ArrayList<String>();
statuses.add(Queue.STATUS_PENDING_APPROVAL);
queues = QueueDao.getCustomersBasedOnStatus(statuses, skipCount);
} catch (ParseException e) {
Log.w(MainActivity.TAG, "Error while retrieving pending queues", e);
}
return queues;
}
#Override
protected void onPostExecute(List<Queue> results) {
TextView nodata = (TextView) layout.findViewById(R.id.nodata);
if(results == null){
nodata.setVisibility(View.VISIBLE);
} else {
if (results.size() <= 0) {
if(!isLoadMore) {
nodata.setVisibility(View.VISIBLE);
}
} else {
nodata.setVisibility(View.GONE);
UltimateRecyclerView queueList = (UltimateRecyclerView) layout.findViewById(R.id.pendinglist);
if(!isLoadMore || queueList.getAdapter() == null){
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity);
ListPendingAdapter listPendingAdapter = new ListPendingAdapter(context, results);
queueList.setLayoutManager(layoutManager);
queueList.setAdapter(listPendingAdapter);
} else {
ListPendingAdapter listPendingAdapter = (ListPendingAdapter) queueList.getAdapter();
listPendingAdapter.getDataset().addAll(results);
listPendingAdapter.notifyDataSetChanged();
}
setLoadMore(queueList);
}
}
if(!isLoadMore) {
ProgressUtil.showProgress(false, view, pb, context);
}
}
private void setLoadMore(final UltimateRecyclerView queueList){
queueList.reenableLoadmore();
queueList.setLoadMoreView(R.layout.custom_bottom_progressbar);
queueList.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
#Override
public void loadMore(int i, int i1) {
LoadPendingCustomer loadPendingCustomer = new LoadPendingCustomer(context, layout, skipCount + 10, true);
loadPendingCustomer.execute();
}
});
}
}
--- fragment xml ---
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
tools:context=".fragments.QueueFragment">
<!-- TODO: Update blank fragment layout -->
<ProgressBar
android:id="#+id/pending_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:visibility="gone" />
<LinearLayout
android:id="#+id/pending_list_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nodata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/nodata"
android:visibility="gone"/>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/pending_swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.marshalchen.ultimaterecyclerview.UltimateRecyclerView
android:id="#+id/pendinglist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
--- custom_bottom_progressbar.xml ---
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/bottomPB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff">
<ProgressBar
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/bottom_progress_bar"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/loading"
android:layout_below="#+id/bottom_progress_bar"
android:layout_marginTop="2dp"
android:gravity="center"/>
</RelativeLayout>
Please help me. Thanks in advance...
i am new to android development. In my app ive implemented an audio player, it plays soounds from teh sd card. i want it to play and show the list of only those audio files that i provide in a folder the app workspace (like the images we give in drawable)
here is the code. Thank you in advance
Play.java
public class Play extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selelctedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
selelctedFile = (TextView)findViewById(R.id.selectedfile);
seekbar = (SeekBar)findViewById(R.id.seekbar);
playButton = (ImageButton)findViewById(R.id.play);
prevButton = (ImageButton)findViewById(R.id.prev);
nextButton = (ImageButton)findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if(null != cursor)
{
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.list, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selelctedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition(){
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter{
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[] { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[] { R.id.displayname, R.id.title, R.id.duration });
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView)view.findViewById(R.id.title);
TextView name = (TextView)view.findViewById(R.id.displayname);
TextView duration = (TextView)view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double)durationInMs/1000.0)/60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.play:
{
if(player.isPlaying())
{
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
}
else
{
if(isStarted)
{
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
}
else
{
startPlay(currentFile);
}
}
break;
}
case R.id.next:
{
int seekto = player.getCurrentPosition() + STEP_VALUE;
if(seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev:
{
int seekto = player.getCurrentPosition() - STEP_VALUE;
if(seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// returning false will call the OnCompletionListener
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
if(isMoveingSeekBar)
{
player.seekTo(progress);
Log.i("OnSeekBarChangeListener","onProgressChanged");
}
}
};
}
play.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_weight="1.0"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:padding="10dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/selectedfile"
android:text="Not file selected"
android:textColor="#android:color/black"
android:gravity="center_horizontal"
android:singleLine="true"
android:ellipsize="middle"/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekbar"
android:max="100"
android:paddingBottom="10dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#android:drawable/screen_background_light">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prev"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/play"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
You need to put your music to assets directory (ie. create subfolder titled 'sounds') and then list the contents of it by method:
myContext.getAssets().list(”sounds");
Then you have to attach the asset to MediaPlayer object:
mediaPlayer.setDataSource(myContext.getAssets().openFd(soundPathInAssets));
You should also see this thread (because the bit of code I presented to you would play whole directory): Play audio file from the assets directory
EDIT: Code from example project (in case of deleting file on my dropbox):
MainActivity.java
public class MainActivity extends Activity {
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView list = (ListView) findViewById(R.id.listView1);
mMediaPlayer = new MediaPlayer();
Button playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mControl.isPlaying()){
mControl.pause();
} else {
mControl.start();
}
}
});
try {
list.setAdapter(new MyAdapter(getAssets().list("music")));
} catch (IOException e) {
e.printStackTrace();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String path = (String) list.getAdapter().getItem(position);
try {
AssetFileDescriptor fd = getAssets().openFd("music/"+path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class MyAdapter extends BaseAdapter {
private String[] content;
public MyAdapter(String[] content){
this.content=content;
}
#Override
public int getCount() {
return content.length;
}
#Override
public Object getItem(int position) {
return content[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = new TextView(getApplicationContext());
TextView cv = (TextView) convertView;
cv.setTextSize(18);
cv.setPadding(8, 8, 8, 8);
}
TextView v = (TextView) convertView;
v.setText(content[position]);
return v;
}
}
MediaPlayerControl mControl = new MediaPlayerControl() {
public void start() {
mMediaPlayer.start();
}
public void pause() {
mMediaPlayer.pause();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
};
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/play"
android:background="#drawable/btn_transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="PlayPause" />
</LinearLayout>
Currently I am working with GalleryView and changing images that is working perfectly fine.
But I want to disable swipe of GalleryView and change the loaded images on button click.
How can i achieve this functionality.
My current Class is As Follow
public class PopUpWindow extends Activity {
TextView closebtn;
Integer[] pics = {
R.drawable.account_icon,
R.drawable.coffee_icon,
R.drawable.help_icon,
R.drawable.menu_icon,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setUpDialogProperties();
this.setFinishOnTouchOutside(false);
setContentView(R.layout.pop_up_dialog);
fetchUI();
}
private void fetchUI(){
closebtn = (TextView)findViewById(R.id.okBtn);
closeDialog();
Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));
ga.setUnselectedAlpha(0.0f);
}
private void closeDialog(){
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setUpDialogProperties() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawableResource(android.R.color.transparent);
android.view.WindowManager.LayoutParams lp = getWindow()
.getAttributes();
lp.gravity = Gravity.BOTTOM;
getWindow().setAttributes(lp);
}
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}
#Override
public int getCount() {
return pics.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
iv.setImageResource(pics[arg0]);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new Gallery.LayoutParams(150,150));
iv.setBackgroundResource(imageBackground);
return iv;
}
}
Thanks in advance
case R.id.leftButton:
int position = mGallery.getSelectedItemPosition() - 1;
if (position < 0)
return;
mGallery.setSelection(position);
break;
case R.id.rightButton:
position = mGallery.getSelectedItemPosition() + 1;
if (position >= mGallery.getCount())
return;
mGallery.setSelection(position);
break;
I will setup the onclick for your next and previous button
Now i should implement infinite scrolling to listview, for this i had found one easiest code that is
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//leave this empty
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - threshold) {
currentPage++;
//load more list items:
loadElements(currentPage);
}
}
}
but now i dont know what to include in the place if loadElements(current Page)
Here is an example code for you. this list scrolls infinite and using thread, it scrolls automatically. (pauses for while and coninues ...)
When you touch the list, list scrolling pauses and when you release it continues to automatic scroll.
If you touch under 100 miliseconds then it will considered item on click.
You can also scroll down or up, it will eventually continue to auto scrolling.
Come to think of it, it has turn into web like list. shame. :(
///////////////////////////////////////////////////////////////////////
List Item XML layout : item.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:padding="20dp"
android:orientation="vertical" >
<TextView
android:background="#00ff00"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:id="#+id/name"
android:textColor="#000000"
android:textSize="26sp"
android:gravity="center"
android:textStyle="bold"/>
</LinearLayout>
///////////////////////////////////////////////////////////////////////
activity layout : activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="25dp"
android:gravity="center"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="450dp"
android:background="#bbbbbb"
android:divider="#000000"/>
</RelativeLayout>
///////////////////////////////////////////////////////////////////////
activiy code (includes adapter and runnable thread) : MainActivity.java
public class MainActivity extends Activity {
ListView list;
long startTime;
long endTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
List<String> mList = new ArrayList<String>();
String str;
for(int i=0;i<10;i++){
str = new String("Data --- "+i);
mList.add(str);
}
LAdapter adapter = new LAdapter(this,0,mList);
list.setAdapter(adapter);
final YourRunnable runy = new YourRunnable();
list.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN ){
startTime= (new Date()).getTime();
runy.onPause();//pausing thread actually pauses scrolling
}
if(event.getAction() == MotionEvent.ACTION_UP){
endTime= (new Date()).getTime();
if((endTime - startTime)<=100){//100 mill second limit for click
//Log.i("ITEM CLICK() ", "item : ");
}
runy.onResume(); //resume scrolling
}
return false;
}
});
new Thread(runy).start();
}
class YourRunnable implements Runnable {
private Object mPauseLock;
private boolean mPaused;
private boolean mFinished;
public YourRunnable() {
mPauseLock = new Object();
mPaused = false;
mFinished = false;
}
public void run() {
while (!mFinished) {
//for loop is not infinite but enough as Integer.MAX_VALUE
for (int index = 0; index < list.getAdapter().getCount(); index++) {
list.smoothScrollToPositionFromTop(list.getLastVisiblePosition() + 1, 0, 10000);
try {
// it helps scrolling to stay smooth as possible (by experiment)
Thread.sleep(10000);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();//putting thread in wait list of mPauseLock object
} catch (InterruptedException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Call this method to pause thread.
*/
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
/**
* Call this method to resume thread.
*/
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();//notify all object that are waiting on the wait list of mPauseLock object
}
}
}
private class LAdapter extends ArrayAdapter{
List<String> mlist;
Context mContext;
LayoutInflater inflater;
public final int HALF_MAX_VALUE = Integer.MAX_VALUE/2;
public final int MIDDLE;
public LAdapter(Context ctx,int resId, List<String> objects){
super(ctx, resId, objects);
mContext = ctx;
mlist = objects;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % mlist.size();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
int relativePos = position % mlist.size();
Log.i("RELATIVE : "," POS:"+relativePos);
return mlist.get(relativePos);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Log.i("POSITION TAG", "POSITION : "+position);
// if(position>(getCount()-1)){
// return null;
// }
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
String model = getItem(position);
holder.name.setText(model);
convertView.setOnClickListener(new ListenerT(model) {
#Override
public void onClick(View v) {
Log.i("CLICK", "ITEM---"+name );
}
});
return convertView;
}
}
//use your own listener to pass parameter
private class ListenerT implements OnClickListener{
String name;
public ListenerT(String nm){
name = nm;
}
#Override
public void onClick(View v) {
}
}
private class ViewHolder{
TextView name;
}
}
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
}
});
}
});