handling click of buttons in list view item android - android

I have a custom list view where each list item has two buttons, one text view and one seek bar where the seek bar visibility is set to gone in list item's XML.
Now what I want to do is on click of button one in the list item I want to hide the text view and display the seek bar of that list item whose button is clicked and show hide the seek bar and display the text view of all other list items.
The code that I have written works well if the total items are less than the views that can be displayed at once in a list view but for a lot of views this does not works.
What I am doing is load a list of files from a a folder into the list view and play the in the list view only
Please tell me where I am going wrong.
Any help would be appreciated.
My Adapter Code:
public class AudioFileListAdapter extends BaseAdapter {
Context context;
ArrayList<String> fileList;
LayoutInflater inflater;
String folder;
ListView mListView;
public MediaPlayer mPlayer;
public Handler seekHandler;
SeekBar mSeekBar;
int clickedPos = -1;
protected static class RowViewHolder {
public TextView fileName;
public Button filePlay;
public Button rate;
public SeekBar fileSeek;
}
public AudioFileListAdapter(Context context, ArrayList<String> fileList,
String folder) {
this.fileList = fileList;
this.context = context;
this.folder = folder;
mListView = (ListView) ((Activity) context)
.findViewById(R.id.Filelistview);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
seekHandler = new Handler();
}
#Override
public int getCount() {
return fileList.size();
}
#Override
public Object getItem(int position) {
return fileList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.audio_file_list_item, null);
viewHolder = new RowViewHolder();
viewHolder.fileName = (TextView) convertView
.findViewById(R.id.file_name);
viewHolder.filePlay = (Button) convertView
.findViewById(R.id.file_play);
viewHolder.filePlay.setTag(position);
viewHolder.rate = (Button) convertView.findViewById(R.id.rate);
viewHolder.fileSeek = (SeekBar) convertView
.findViewById(R.id.file_seek);
viewHolder.filePlay.setOnClickListener(mListener);
viewHolder.rate.setOnClickListener(mListener);
convertView.setTag(viewHolder);
} else {
viewHolder = (RowViewHolder) convertView.getTag();
}
viewHolder.fileName.setText(fileList.get(position));
return convertView;
}
OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.file_play)
{
final int position = mListView.getPositionForView((View) v
.getParent());
Log.d("position"+position, "count"+mListView.getCount());
for (int i = 0 ; i < mListView.getChildCount(); i++) {
RowViewHolder viewholder = (RowViewHolder) ((View) mListView
.getChildAt(i)).getTag();
if (i == position) {
String path = Environment.getExternalStorageDirectory()
.toString()
+ "/analyser/"
+ folder
+ "/"
+ fileList.get(i);
mSeekBar = viewholder.fileSeek;
Log.d("IN the click "+i,path);
// mSeekBar.setEnabled(false);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(mPlayer != null && fromUser){
mPlayer.seekTo(progress);
}
}
});
viewholder.fileSeek.setVisibility(View.VISIBLE);
viewholder.fileName.setVisibility(View.GONE);
play(path);
} else {
viewholder.fileSeek.setVisibility(View.GONE);
viewholder.fileName.setVisibility(View.VISIBLE);
}
}
}
if (v.getId() == R.id.rate) {
}
}
};
public void play(String path) {
if (mPlayer == null) {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mSeekBar.setMax(mPlayer.getDuration());
mp.start();
seekUpdation();
}
});
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
mPlayer = null;
seekHandler.removeCallbacks(run);
}
});
}
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
seekHandler.removeCallbacks(run);
}
try {
mPlayer.setDataSource(path);
mPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mPlayer != null) {
seekUpdation();
}
}
};
public void seekUpdation() {
if (mPlayer != null) {
mSeekBar.setProgress(mPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
}
}

You have to set the listeners for the button in the Adapter class getView method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.audio_file_list_item, null);
viewHolder = new RowViewHolder();
viewHolder.fileName = (TextView) convertView.findViewById(R.id.file_name);
viewHolder.filePlay = (Button) convertView.findViewById(R.id.file_play);
viewHolder.filePlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
// Do Your Work Here
}
});
viewHolder.filePlay.setTag(position);
viewHolder.rate = (Button) convertView.findViewById(R.id.rate);
viewHolder.fileSeek = (SeekBar) convertView.findViewById(R.id.file_seek);
viewHolder.filePlay.setOnClickListener(mListener);
viewHolder.rate.setOnClickListener(mListener);
convertView.setTag(viewHolder);
} else {
viewHolder = (RowViewHolder) convertView.getTag();
}
viewHolder.fileName.setText(fileList.get(position));
return convertView;
}

Related

How to set onclick listener for two Gridview in same layout?

i have two custom GridView, I want to set Onclick Listener for first GridView, i did it inside its adapter , working fine ... but when generate items in second GridView the onclick listener read values from second GridView when i press on item in first GridView!
The onclick listener working fine if the second GridView empty
I have no idea how to fix this
The problem with holder.tvgroup1 and holder.tvgroup_delete_icon
Thanks
First GridView Adapter
public class GroupGeneratedAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
GroupGeneratedAdapter(GroupMakerG groupMakerG, ArrayList<String> UserNameinput) {
// TODO Auto-generated constructor stub
result = UserNameinput;
context = groupMakerG;
// imageId=prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tvgroup, tvgroup1;
ImageView tvgroup_delete_icon;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
// View rowView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group_generated_original, parent, false);
}
holder.tvgroup = (TextView) convertView.findViewById(R.id.tvgroup);
holder.tvgroup1 = (TextView) convertView.findViewById(R.id.tvgroup1);
holder.tvgroup_delete_icon = (ImageView) convertView.findViewById(R.id.tvgroup_delete_icon);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tvgroup.setText(String.valueOf(position + 1) + "-");
holder.tvgroup1.setText(result.get(position));
// holder.img.setImageResource(imageId[position]);
holder.tvgroup_delete_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GroupMakerG.GroupOfNames.remove(position);
GroupMakerG.MainGroup.invalidateViews();
if (GroupMakerG.arraySugestion.size() > 0) {
GroupMakerG.arraySugestion.clear();
GroupMakerG.makeSuggestions();
} else {
GroupMakerG.makeSuggestions();
}
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.No_Of_Groups.setText("");
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
GroupMakerG.GroupNameLength.setText(String.valueOf(GroupMakerG.GroupOfNames.size()));
}
});
holder.tvgroup1.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Modify Item No." + " " + (position + 1));
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(context).inflate(R.layout.modify_name_mainlist, (ViewGroup) parent.findViewById(android.R.id.content), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.client_name_input);
input.setText(GroupMakerG.GroupOfNames.get(position));
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String m_Text = input.getText().toString();
if (m_Text.trim().equals("")) {
// Toast.makeText(context, "You should enter name", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(context,context.getString(R.string.group_you_should_enter_name), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
GroupMakerG.GroupOfNames.set(position, m_Text);
GroupMakerG.MainGroup.invalidateViews();
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
Toast toast = Toast.makeText(context, context.getString(R.string.group_item_changed), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return false;
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+ result.get(position), Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Second GridView Adapter
public class GroupGeneratedAdapterG extends BaseAdapter {
private ArrayList<String> resultg;
int[] imageId;
private static LayoutInflater inflaterg = null;
private static int generated_group_counter;
Context contextg;
GroupGeneratedAdapterG(GroupMakerG groupMaker, ArrayList<String> UserNameoutput) {
// TODO Auto-generated constructor stub
resultg = UserNameoutput;
contextg = groupMaker;
// imageId=prgmImages;
inflaterg = (LayoutInflater) contextg.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
generated_group_counter = 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return resultg.size();
}
#Override
public Object getItem(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
#Override
public long getItemId(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
public class Holder {
TextView tvgroupg, tvgroup1g;
// ImageView img;
}
#Override
public View getView(final int positiong, View convertViewg, ViewGroup parentg) {
// TODO Auto-generated method stub
generated_group_counter = generated_group_counter + 1;
Holder holderg = new Holder();
// View rowView;
if (convertViewg == null) {
convertViewg = inflaterg.inflate(R.layout.group_generated_generated, parentg, false);
}
holderg.tvgroupg = (TextView) convertViewg.findViewById(R.id.tvgroupg);
holderg.tvgroup1g = (TextView) convertViewg.findViewById(R.id.tvgroup1g);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
String[] ary = resultg.get(positiong).split("!##%");
if (ary[1].length() > 4) {
if (ary[1].substring(0, 5).equals("Group")) {
holderg.tvgroupg.setText("");
holderg.tvgroup1g.setText(ary[1]);
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
convertViewg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(contextg, "You Clicked "+ String.valueOf(resultg.get(positiong)), Toast.LENGTH_LONG).show();
}
});
return convertViewg;
}
}

Listview not generating views on second time with different layouts?

Hi i have created a listview,In that i inflated four layout, my data set is images, text,audio and Video. so i inflating the layouts accordingly.Once the data is coming from Api,and images is being cached,and audio video and text is being stored in folder and sqlite respectively. But when i open second time the listview showing the data randomly or sometime unordered. even sometime not showing whole data. here is my adapter's code.
public class ListViewAdapter extends BaseAdapter {
ArrayList<ListModel> myList = new ArrayList<ListModel>();
LayoutInflater inflater;
Context context;
int flag = 0;
private static final int TYPE_ITEM1 = 1;
private static final int TYPE_ITEM2 = 2;
private static final int TYPE_ITEM3 = 3;
private static final int TYPE_ITEM4 = 4;
private String url;
private String vPath;
private MediaPlayer mp;
public ListViewAdapter(Context context, ArrayList<ListModel> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
int type;
#Override
public int getItemViewType(int position) {
ListModel listModel = myList.get(position);
String data = listModel.getType();
if (data.equals("Text")) {
type = TYPE_ITEM1;
} else if (data.equals("Image")) {
type = TYPE_ITEM2;
} else if (data.equals("Audio")) {
type = TYPE_ITEM3;
}else if(data.contains("Video")){
type=TYPE_ITEM4;
}
return type;
}
#Override
public int getViewTypeCount() {
return myList.size() + 1;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListModel getItem(int position) {
// return myList.get(position);
if (position >= myList.size()) {
return null;
}
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder holder = null;
TextView textView = null;
ImageView imageView = null;
VideoView vPlayer = null;
Button pause = null;
Button play = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + v + " type = " + type);
if (v == null) {
holder = new ViewHolder();
if (type == TYPE_ITEM1) {
v = inflater.inflate(R.layout.list_text, null);
textView = (TextView) v.findViewById(R.id.text);
} else if (type == TYPE_ITEM2) {
v = inflater.inflate(R.layout.list_image, null);
imageView = (ImageView) v.findViewById(R.id.imgView);
} else if (type == TYPE_ITEM3) {
v = inflater.inflate(R.layout.list_audio, null);
play = (Button) v.findViewById(R.id.btn_play);
pause = (Button) v.findViewById(R.id.stop);
} else if (type == TYPE_ITEM4) {
v = inflater.inflate(R.layout.list_video, null);
vPlayer = (VideoView) v.findViewById(R.id.video_player);
}
holder.textView = textView;
holder.videoPlayer = vPlayer;
holder.imageView = imageView;
holder.play = play;
holder.stop = pause;
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
ListModel model = myList.get(position);
if (holder.play != null) {
holder.play.setId(position);
}if (holder.videoPlayer!=null){
holder.videoPlayer.setId(position);
}if (holder.stop!=null){
holder.stop.setId(position);
}
String datatype = model.getType();
if (datatype.equals("Text")) {
holder.textView.setText(model.getData());
} else if (datatype.equals("Image")) {
UrlImageViewHelper.setUrlDrawable(holder.imageView, model.getData());
} else if (datatype.equals("Audio")) {
url = model.getData();
}else if (datatype.equals("Video")){
vPath=model.getData();
}
if (holder.play != null) {
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = view.getId();
ListModel model = myList.get(i);
String audioUri = model.getData();
new PlayMusicFromPath().execute(audioUri);
}
});
if (holder.stop!=null){
holder.stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});}
if (holder.videoPlayer!=null) {
final ViewHolder finalHolder = holder;
holder.videoPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int videoId = view.getId();
ListModel model1 = myList.get(videoId);
String videoUrl = model1.getData();
finalHolder.videoPlayer.setVideoPath(videoUrl);
}
});
}
}
return v;
}
public static class ViewHolder {
public TextView textView;
public ImageView imageView;
public Button play, stop;
public VideoView videoPlayer;
}
public void audioPlayer(String fileName) {
//set up MediaPlayer
mp = new MediaPlayer();
try {
mp.setDataSource(fileName);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
class PlayMusicFromPath extends AsyncTask<String, String, String> {
// Show Progress bar before downloading Music
#Override
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
audioPlayer(f_url[0]);
return null;
}
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
System.out.print(file_url);
}
}
You only set the Button play when type == TYPE_ITEM3, but you always call holder.play.setOnClickListener. Hence you either only call the setOnClickListener method when play is not null, e.i:
if(holder.play != null){
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//mycode
}
});
}
Or you always set the play button to a Button object

Change Listview item image on click in Android

i want to change particular listview images when click on nect and prev button but Changed all list view images when click on next and prev button
public class ListAdapter extends ArrayAdapter<String>{
Context context;
String imgurl;
String[] imageUrls;
int i=1;
ViewHolder holder = null;
ArrayList<String> strimgview,strstreetname,strLocation,strSquarefootage,strPrice,strPosted,strURL,strId;
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true).build();
public ListAdapter(Context context,ArrayList<String> strimgview, ArrayList<String> strstreetname,
ArrayList<String> strLocation,ArrayList<String> strSquarefootage,
ArrayList<String> strPrice,ArrayList<String> strPosted,
ArrayList<String> strId,ArrayList<String> strURL)
{
super(context, R.layout.propertyrow,strstreetname);
this.context= context;
this.strimgview= strimgview;
this.strstreetname= strstreetname;
this.strLocation= strLocation;
this.strSquarefootage= strSquarefootage;
this.strPrice= strPrice;
this.strPosted= strPosted;
this.strURL= strURL;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View row = convertView;
if (row == null) {
row=mInflater.inflate(R.layout.propertyrow, parent,false);
holder = new ViewHolder();
holder.imgProperty =(ImageView) row.findViewById(R.id.npTupleImage);
holder.txtStreetName= (TextView) row.findViewById(R.id.npTupleProjectName);
holder.txtLocation= (TextView) row.findViewById(R.id.npTupleBuilder);
holder.txtSquareFotage= (TextView) row.findViewById(R.id.npTupleProjectAddress);
holder.txtPrice =(TextView) row.findViewById(R.id.npTupleProjectDistance);
holder.txtprev =(TextView) row.findViewById(R.id.prev);
holder.txtnext =(TextView) row.findViewById(R.id.next);
//txtprev.setVisibility(View.INVISIBLE);
//txtnext.setVisibility(View.INVISIBLE);
holder.imglike= (ImageView) row.findViewById(R.id.unsavebtn);
holder.imglike.setVisibility(View.INVISIBLE);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
// txtposted.setText("EnteredDate :"+strPosted.get(position));
holder.txtStreetName.setText("Street Name :"+strstreetname.get(position));
holder.txtLocation.setText("Location :"+strLocation.get(position));
holder.txtSquareFotage.setText("SquareFootage :"+strSquarefootage.get(position));
holder.txtPrice.setText("Price :$"+strPrice.get(position));
holder.imgProperty.setTag(position);
// Log.d("Img",strimgview.get(position));
try{
// ArrayList<String> imgurl=new ArrayList<String>();
imgurl= ""+strimgview.get(position);
imageUrls=imgurl.split("\\|\\|");
for(int j=0;j<imageUrls.length-1;j++)
imageLoader.displayImage(imageUrls[i], holder.imgProperty, options);
}
catch(Exception e)
{
Toast.makeText(context, "Load"+e, Toast.LENGTH_LONG).show();
}
holder.imglike.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(context, "Want to save", Toast.LENGTH_LONG).show();
}
});
holder.txtprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(i!=1)
{
i--;
imageLoader.displayImage(imageUrls[i], holder.imgProperty, options);
Log.d("imageUrlnew ",imageUrls[i]);
}
}
catch(Exception e)
{
// Toast.makeText(context, "next"+e, Toast.LENGTH_LONG).show();
}
notifyDataSetChanged();
}
});
holder.txtnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if((i<imageUrls.length-1))
{
i++;
imageLoader.displayImage(imageUrls[i], holder.imgProperty, options);
Log.d("imageUrlnew ",imageUrls[i]);
}
}
catch(Exception e)
{
// Toast.makeText(context, "prev"+e, Toast.LENGTH_LONG).show();
}
notifyDataSetChanged();
}
});
return row;
}
class ViewHolder {
ImageView imgProperty;
TextView txtprev,txtnext;
TextView txtStreetName;
TextView txtLocation;
TextView txtSquareFotage;
TextView txtPrice;
ImageView imglike;
ProgressBar progressBar;
}
}
Please help me how can fix this issue
Thanks In Advance
this is not a perfect solution if it works according to ur requirment. then update the solution withot switch.
lstviewHomeList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
switch (position) {
case 0:
Button btnprev = (Button ) arg1.findViewById(R.id.button_id);
//same for image and any widgetn your adapter layout xml
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//do what u want
}
});
break;
default:
break;
}
}
});

correctly displays a seekbar in custom adapter

I have a list in which each element on a player. When I click on "start" and a song starts playing strip seekbar starts moving. when click on the "stop" the song stops playing and the strip stops. But if while moving the strip I scroll list and it goes off the screen, it starts to move another strip that is on the same position in the visible area of the screen.
public class RecordAdapter extends BaseAdapter {
private MediaPlayer mediaPlayer;
private LayoutInflater inflater;
private ArrayList<RecordBean> recordBeans;
private final Handler handler = new Handler();
private Context ctx;
private int global_position;
...
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.recorditem, parent, false);
holder = new ViewHolder();
holder.date = (TextView) view.findViewById(R.id.recordate);
holder.seekBar = (SeekBar) view.findViewById(R.id.seekBar);
holder.start = (Button) view.findViewById(R.id.btnStart);
holder.stop = (Button) view.findViewById(R.id.btnStop);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.date.setText(" " + recordBeans.get(position).getDate());
holder.start.setTag(position);
holder.stop.setTag(position);
holder.seekBar.setTag(position);
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(final SeekBar seekBar, final int i, boolean b) {
if (b && (Integer)seekBar.getTag()==global_position) {
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
holder.start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
releaseMP();
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(recordBeans.get((Integer) v.getTag()).getFile());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
global_position = position;
holder.start.setTextColor(Color.RED);
holder.seekBar.setMax(mediaPlayer.getDuration());
startPlayProgressUpdater(holder.seekBar,holder.start);
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
if (mediaPlayer == null) {
return;
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
Log.d("LOG_TAG", "onCompletion");
holder.start.setTextColor(Color.WHITE);
}
});
}
});
holder.stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer == null)
return;
if ((Integer) v.getTag() == global_position) {
mediaPlayer.stop();
}
}
});
return view;
}
private void releaseMP() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static class ViewHolder {
TextView date;
SeekBar seekBar;
Button start;
Button stop;
}
public void startPlayProgressUpdater(final SeekBar seek, final Button start) {
seek.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater(seek,start);
}
};
handler.postDelayed(notification, 1000);
} else {
mediaPlayer.pause();
seek.setProgress(0);
}
}
}
EDIT:
I added geter and seter in recordBean
public int getSeekPos() {
return SeekPos;
}
public void setSeekPos(int seekPos) {
SeekPos = seekPos;
}
and
holder.seekBar.setProgress(recordBeans.get(position).getSeekPos());
holder.date.setText(" " + recordBeans.get(position).getDate());
and
#Override
public void onProgressChanged(final SeekBar seekBar, final int i, boolean b) {
if (b && (Integer)seekBar.getTag()==global_position) {
// mediaPlayer.seekTo(i);
recordBeans.get(position).setSeekPos(i);
}
}
but I think it left something extra in my code
The list item is being recycled when it leaves the screen.
You could try to call this in getView:
holder.seekBar.clearFocus();
This is a tricky process, but you can do this in the following way, as I have seen that you have created a List of RecordBean class. So what you can do is you have to create a Getter Setter in RecordBean for storing the position of you SeekBar like:
public void setSeekPos(int pos) {
this.pos = pos;
}
public int getSeekPos() {
return pos;
}
In your adapter below the line
holder.date.setText(" " + recordBeans.get(position).getDate());
set the progress of seekBar like this: holder.seekBar.setProgress(recordBeans.get(position).getSeekPos());
and inside the onProgressChanged add the following line recordBeans.get(position).setSeekPos(i);
This will resolve your issue.
Please let me know if it's working or not.
Thanks

android inconsistency in listiew multiple layouts inflation

I use PulltoRefresh listview and I use 3 layouts.
1. Gaming Layout(Should be inflated when linkedlist item starts with "gm")
2. Adlayout(Should be inflated when linkedlist item starts with "ad")
3.Normal Listview layout(in all other cases)
Here is the code
mListItems = new LinkedList<String>();
mListItems.add(0,"hi1");
mListItems.add(1,"hi2");
mListItems.add(2,"gm");
mListItems.add(3,"hi3");
mListItems.add(4,"ad");
mListItems.add(5,"hi4");
((PullToRefreshListView) getListView())
.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
;
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
// mListItems.addFirst("Added after refresh...");
// parseJson("IndigoFM_06212013.json");
mListItems.addFirst("how are you");
mListItems.addFirst("ad");
mListItems.addFirst("gm");
mListItems.addFirst("the end");
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) getListView()).onRefreshComplete();
super.onPostExecute(result);
}
}
Here is the adapter code
private class basicListAdapter extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return mListItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mListItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater inflater = LayoutInflater
.from(getApplicationContext());
if ((mListItems.get(position).startsWith("gm"))) {
v = inflater.inflate(R.layout.gaminglayout, null);
} else if ((mListItems.get(position).startsWith("ad"))) {
v = inflater.inflate(R.layout.adlayout, null);
} else if(!(mListItems.get(position).startsWith("gm")) && !(mListItems.get(position).startsWith("ad"))) {
v = inflater.inflate(R.layout.listinflate, null);
}
viewHolder holder = new viewHolder();
adViewHolder adHolder = new adViewHolder();
gamingViewHolder gamingHolder = new gamingViewHolder();
if ((mListItems.get(position).startsWith("ad"))) {
adHolder.adDetails = (TextView) v.findViewById(R.id.adText);
v.setTag(adHolder);
} else if ((mListItems.get(position).startsWith("gm"))) {
gamingHolder.gamingButton = (Button) v
.findViewById(R.id.gamingButton);
gamingHolder.gamingButton .setOnClickListener(mOngamingButtonClickListener);
v.setTag(gamingHolder);
}else if(!(mListItems.get(position).startsWith("gm")) && !(mListItems.get(position).startsWith("ad"))){
holder.rjName = (TextView) v.findViewById(R.id.rjName);
holder.textViewName = (TextView) v
.findViewById(R.id.textViewName);
holder.likeLayout = (LinearLayout) v
.findViewById(R.id.likeLayout);
holder.commentLayout = (LinearLayout) v
.findViewById(R.id.commentLayout);
holder.likeLayout
.setOnClickListener(mOnLikeLayoutClickListener);
holder.commentLayout
.setOnClickListener(mOnCommentLayoutClickListener);
v.setTag(holder);
}
}
if (mListItems.get(position) != null) {
// if(!(mListItems.get(position).startsWith("1"))){
if (!(v.getTag() instanceof adViewHolder)) {
if(!(v.getTag() instanceof gamingViewHolder)){
viewHolder holder = (viewHolder) v.getTag();
holder.textViewName.setText(mListItems.get(position));
}
}
}
return v;
}
}
Now the issue is that after I pull to refresh, The entries which start with "gm" are being shown in normal listview layout but not the gaming layout.
In a way to say incorrect layout is being inflated

Categories

Resources