Update TextView within custom ListView - android

I'm trying to update the TextView within a custom ListView at a set time interval, for example the TextView will update every 200ms however I can't figure out how to do this. The object updates with a number internally and I would like to show that in the mTitleText Textview however as the code below shows at the moment I can only achieve it when the user presses a button.
public class ListAdapter extends BaseAdapter {
private ArrayList< Object > mObjects;
private int mNumObjs = 0;
private LayoutInflater mLayoutInflater;
private Context mContext;
public ListAdapter ( Context context, ArrayList< Object > objects ) {
mObjects;= objects;
mLayoutInflater = LayoutInflater.from(context);
mContext = context;
}
public int getCount() {
return mObjects;.size();
}
public Object getItem( int position ) {
return mObjects;.get(position);
}
public long getItemId( int position ) {
return position;
}
public void addObject( Object obj) {
obj.setId(mNumObjs);
mObjects.add( obj );
(mNumObjs);++;
notifyDataSetChanged();
}
public void deleteObject( int pos ) {
mObjects;.remove( pos );
notifyDataSetChanged();
}
public View getView( final int position, View convertView, ViewGroup parent ) {
final TimerView holder;
if( convertView == null ) {
convertView = mLayoutInflater.inflate( R.layout.customlistview, null );
holder = new HolderView();
holder.mListPosition = position;
holder.mDeleteButton = (Button)convertView.findViewById(R.id.Delete);
holder.mDeleteButton.setText( "Button No: " + position );
holder.mDeleteButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteObject(holder.mListPosition);
}
});
holder.mButton = (Button)convertView.findViewById(R.id.Button);
holder.mButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Object obj = mObjects.get(holder.mListPosition);
mTitleText.setText(obj.getNum());
}
});
convertView.setTag(holder);
}
else {
holder = (TimerView) convertView.getTag();
}
holder.mListPosition = position;
holder.mDeleteButton.setText( "Button No: " + position );
return convertView;
}
class HolderView{
int mListPosition;
Button mDeleteButton;
Button mButton;
TextView mTitleText;
}
}

Okay I managed to figure this out myself, if your updates don't need to be very frequent ( >1 sec ) you can use notifyDataSetChanged() however if like me you need to constantly update the listview every 200ms or so you need to iterate through the visible objects on the list view and update it.
private Runnable showUpdate = new Runnable(){
public void run(){
mAdapter.updateList();
//mAdapter.notifyDataSetChanged();
int count = mListView.getCount();
for( int i = 0; i < count; i ++ )
{
View convertView = mListView.getChildAt( i );
if( convertView != null )
{
HolderView holder = (HolderView) convertView.getTag();
Object obj = (Object)mAdapter.getItem( holder.mListPosition );
holder.mTitleText.setText( obj.getText() );
}
}
}
};
Thread mThread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(100);
mHandler.post(showUpdate);
//mHandler.sendEmptyMessage(MSG_UPDATE);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

Update the text in your list mObjects and call notifyDataSetChanged() on your adapter.

Related

notifyDataSetChanged Android ListView and VideoView

My app has a ListView and each row contains a TextView running a timer and a video player (ExoMediaPlayer) in each row
I refresh each row by listAdapter.notifyDataSetChanged() to update the timer TextView every second. It works fine as shown in the below code.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
updateTextView();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
private void updateTextView() {
if (listView != null) {
for (int i = 0; i <= listView.getListChildCount(); i++) {
View v = listView.getListChildAt(i);
if (v != null) {
for(int x=firstVisibleRow;i<=lastVisibleRow;i++)
{
HomeListItem data;
data = listMockData.get(i);
HListAdapter.notifyDataSetChanged();
TextView t = (TextView) v.findViewById(R.id.tvTimer);
t.setText(data.getElapsedTime());
}
}
}
}
}
Adapter
public HListAdapter(Context context, ArrayList<HomeListItem> listData) {
c = context;
layoutInflater = LayoutInflater.from(context);
this.listData = listData;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return listData.indexOf(getItem(position));
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.location_list_row, null);
holder.timer= (TextView) convertView.findViewById(R.id.timer);
holder.videoPlayer = (EMVideoView) convertView.findViewById(R.id.videoPlayer);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
newsItem = listData.get(position);
holder.timer.setText(newsItem.getElapsedTime());
String videolink = "http://www.someurl.com/";
holder.videoPlayer.setVideoURI(Uri.parse(videolink ));
holder.videoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.videoPlayer.start();
}
});
return convertView;
}
static class ViewHolder {
TextView timer;
EMVideoView videoPlayer;
}
Problem
The above code works good and the timer TextView updates the time every second.
But the problem i am facing is the VideoPlayer is being reloaded every second, the video does not play due to HListAdapter.notifyDataSetChanged();
if i remove the notifyDataSetChanged() video plays on the listview but the timer TextView does not get updated.
Any possibility to refresh/update the TextView timer only every second.
Any logic or method to solve the problem and make the video play and also the timer to be updated every second?
I think your logic in updateTextView method is wrong. See my comments
private void updateTextView() {
if (listView != null) {
for (int i = 0; i <= listView.getListChildCount(); i++) {
View v = listView.getListChildAt(i);
if (v != null) {
for(int x=firstVisibleRow;i<=lastVisibleRow;i++) // what is x here ?!!
{
HomeListItem data;
data = listMockData.get(i);
HListAdapter.notifyDataSetChanged();
TextView t = (TextView) v.findViewById(R.id.tvTimer);
t.setText(data.getElapsedTime()); // here you are setting the same text over and over
}
}
}
}
}
Instead go with this
private void updateTextView() {
if (listView != null) {
for (int i = 0; i < listView.getListChildCount(); i++) {
View v = listView.getListChildAt(i);
HomeListItem data;
data = listMockData.get(firstVisibleRow + i);
TextView t = (TextView) v.findViewById(R.id.tvTimer);
t.setText(data.getElapsedTime());
}
}
}
no need of notifyDataSetChanged()

How to increment TextView value outside ListView when ListView button is clicked in Android

I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});

Android list view change text when row is deleted

I have a ListView, which has an hidden button which become visible on user long click on row.
If someone clicks this button, the row is deleted.
My rows are composed by transactions, and in the same Activity i got a TextView displaying the amount.
When I add a transaction, my text is changed and the budget updated. My problem is updating it when an user clicks the button and deletes a row.
here is my adapter class
public class HomePageListAdapter extends ArrayAdapter<TRANSAZIONE> {
ArrayList<TRANSAZIONE> transazioni;
public HomePageListAdapter(Context context, int textViewResourceId,
ArrayList<TRANSAZIONE> objects) {
super(context, textViewResourceId, objects);
transazioni = objects;
}
TRANSAZIONE transazione;
NumberFormat formatter = new DecimalFormat("#0.00");
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapter_home_page_list, null);
TextView tvDesc = (TextView) view.findViewById(R.id.tvDescription);
TextView tvAmou = (TextView) view.findViewById(R.id.tvAmount);
final Button btnElimina = (Button) view.findViewById(R.id.btnElimina);
transazione = transazioni.get(position);
String dText = transazione.getDescription();
String aText = "";
if(transazione.getAmount() != null) {
aText = formatter.format(transazione.getAmount()) + " €";
if (transazione.getAmount() > 0) {
tvAmou.setTextColor(Color.GREEN);
} else {
tvAmou.setTextColor(Color.RED);
}
}
tvDesc.setText(dText);
tvAmou.setText(aText);
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
btnElimina.setVisibility(View.VISIBLE);
return false;
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnElimina.getVisibility() == View.VISIBLE) {
btnElimina.setVisibility(View.GONE);
}
}
});
btnElimina.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new TRANSAZIONE().Delete(TRANSAZIONE.class, getContext(), "where id = '" + transazioni.get(position).getId() + "'");
Toast.makeText(getContext(), "Transazione eliminata.", Toast.LENGTH_SHORT).show();
transazioni.remove(position);
notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(getContext(), "Errore non gestito.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
It works properly, and I have no problems updating my layout.
** And this is the method which updates my TextView's text and calls the Adapter. It's in the Activity**
public void LoadTotal() throws Exception {
#SuppressWarnings("unchecked")
ArrayList<TRANSAZIONE> transazioni = (ArrayList<TRANSAZIONE>) new TRANSAZIONE().SelectAll(TRANSAZIONE.class, getContext(), "");
Double totale = Settings.getLimitAmount();
//prendo solo quelle del mese corrente
if (transazioni.size() > 0) {
int numeroAggiornamento = Settings.getResettingDay();
Calendar today = Calendar.getInstance();
Calendar transactionDate = Calendar.getInstance();
Calendar lastChangeDate = Calendar.getInstance();
lastChangeDate.set(Calendar.DAY_OF_MONTH, numeroAggiornamento);
if (today.get(Calendar.DAY_OF_MONTH) < numeroAggiornamento) {
lastChangeDate.add(Calendar.MONTH, -1);
}
for (TRANSAZIONE t : transazioni) {
transactionDate.setTime(t.getDate());
if (transactionDate.compareTo(lastChangeDate) == -1) {
transazioni.remove(t);
} else {
totale += t.getAmount();
}
}
}
if (transazioni.size() == 0) {
transazioni.add(new TRANSAZIONE("Nessuna transazione per il mese in corso.", null, null));
}
HomePageListAdapter adapter = new HomePageListAdapter(getContext(), R.layout.adapter_home_page_list, transazioni);
lvTransactions.setAdapter(adapter);
tvBudget.setText(formatter.format(totale));
}
My problem is the following:
When I delete a row, it disappears from the list, but I can't intercept this in my Activity.
I need someway to call the method LoadTotal() when my row is deleted.
Any help will be appreciated.
Thanks all and sorry for my not perfect English.
The cleanest way of doing it is by using a DataSetObserver.
Inside your activity you have this object:
private DataSetObserver adapterObserver = new DataSetObserver() {
#Override
public void onChanged(){
// here you call your method
LoadTotal();
}
}
and then you register/unreguster this observer during onResume/onPause
#Override
public void onResume(){
super.onResume();
LoadTotal(); // update with latest values
adapter.registerDataSetObserver(adapterObserver);
}
#Override
public void onPause(){
super.onPause();
adapter.unregisterDataSetObserver(adapterObserver);
}
edit: some debug info for the op.
here is the code for notifyDataSetChanged() from BaseAdapter
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
and then inside DataSetObservable is simply looping through the list of observers
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
That means there's very little to actually go wrong there. But it's important to understand what is happening. So my suggestion is to put a breakpoint on all the method calls: onPause, onResume, onChanged and the line you call notifyDataSetChanged. And run it with the debugger, so you can see what is being called when and find out why it's not working.
In your adapter class
public class HomePageListAdapter extends ArrayAdapter<TRANSAZIONE> {
Context context;
ArrayList<TRANSAZIONE> transazioni;
public HomePageListAdapter(Context context, int textViewResourceId,
ArrayList<TRANSAZIONE> objects) {
super(context, textViewResourceId, objects);
transazioni = objects;
this.context=context;
}
TRANSAZIONE transazione;
NumberFormat formatter = new DecimalFormat("#0.00");
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapter_home_page_list, null);
TextView tvDesc = (TextView) view.findViewById(R.id.tvDescription);
TextView tvAmou = (TextView) view.findViewById(R.id.tvAmount);
final Button btnElimina = (Button) view.findViewById(R.id.btnElimina);
transazione = transazioni.get(position);
String dText = transazione.getDescription();
String aText = "";
if(transazione.getAmount() != null) {
aText = formatter.format(transazione.getAmount()) + " €";
if (transazione.getAmount() > 0) {
tvAmou.setTextColor(Color.GREEN);
} else {
tvAmou.setTextColor(Color.RED);
}
}
tvDesc.setText(dText);
tvAmou.setText(aText);
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
btnElimina.setVisibility(View.VISIBLE);
return false;
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnElimina.getVisibility() == View.VISIBLE) {
btnElimina.setVisibility(View.GONE);
}
}
});
btnElimina.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new TRANSAZIONE().Delete(TRANSAZIONE.class, getContext(), "where id = '" + transazioni.get(position).getId() + "'");
Toast.makeText(getContext(), "Transazione eliminata.", Toast.LENGTH_SHORT).show();
transazioni.remove(position);
notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(getContext(), "Errore non gestito.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
You can call the method of your activity like
((YourActivityName)context).LoadTotal();

Set text to TextView at a particular position inside a ListView

I am using a ListView with a custom Adapter. I have two TextView inside each row. I need to change the text of these TextView only for the textViews which I click. How can I achieve it?
I have a method inside my CustomAdapter where I initialise the TextView's
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete, block;
TextView itemName, showResult;
int triedOnce;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private ArrayList<String> mList;
public static final String API_KEY = "MYAPIKEY";
public MainListAdapter(Context context, ArrayList<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
if(position%2 == 0){
convertView.setBackgroundResource(R.drawable.lis_bg);
}else if(position%2 == 1){
convertView.setBackgroundResource(R.drawable.ls_eppadi_bg);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
block = (TextView) viewSlide.findViewById(R.id.tv_menu_block);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//perform cancel
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//perform delete
}
});
block.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//perform block
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
return convertView;
}
//this is where the textview's are initialised
private void fillItemData(View convertView, final int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
showResult = (TextView)viewMain.findViewById(R.id.tv_show);
itemName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new PushTask().execute(position);
triedOnce = 0;
}
});
itemName.setBackgroundColor(currColor);
showResult.setBackgroundColor(currColor);
itemName.setText(mList.get(position));
}
class PushTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
itemName.setVisibility(View.GONE);
showResult.setVisibility(View.VISIBLE);
//set text here based on the position
showResult.setText("SENDING");
}
#Override
protected Integer doInBackground(Integer... position) {
int post = position[0];
int respCode = 0;
//perform my network operations
return respCode;
}
#Override
protected void onPostExecute(Integer response) {
switch(response) {
case 1:
//set text here
showResult.setText("SENT");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
showResult.setVisibility(View.GONE);
itemName.setVisibility(View.VISIBLE);
}
}, 2000);
break;
case 2:
//set text here
showResult.setText("PLEASE WAIT!");
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
showResult.setVisibility(View.GONE);
itemName.setVisibility(View.VISIBLE);
}
}, 2000);
break;
case 3:
//set text here
showResult.setText("FAILED!");
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
showResult.setVisibility(View.GONE);
itemName.setVisibility(View.VISIBLE);
}
}, 2000);
break;
case 4:
//set text here
showResult.setText("FAILED!");
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
showResult.setVisibility(View.GONE);
itemName.setVisibility(View.VISIBLE);
}
}, 2000);
break;
default:
break;
}
}
}
}
Now I need to change the itemName and showResult's text based on the position where the user clicks. The itemName.setOnClickListener has the AsyncTask where I will changing the text of these textViews.
Currently it changes for the last row of the listView.
How do I change it for the position selected.
Thanks in advance.
Override the getView(...) function of CustomAdapter,where one of the arguments is int position .
Don't forget to use convertView, holder and settag/gettag for smooth scrolling and correct references
Update:
in getView put:
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//perform update on textView here
}
});
Also we need reference of convertView in postExecute(). You can pass this reference in AsycTask arguments or set getter setter for the adapter and get clicked reference in asyctask postexecute()
create a model(POJO) class first
with your two strings and one boolean value call it as isChecked
add getters and setters to it
set values(list data) to your arraylist and keep setIsChecked value to false for the first time. like this
ArrayList<model> list = new ArrayList<model>();
list.add(new model("string1","string2",false);
list.add(new model("string11","string22",false);
and so on
now onItemClickListener use for loop like this
for(int i = 0 ; i < list.size; i++){
list.get(i).setIsChecked(false);
}
list.get(itemClickedPosition).setIsChecked(true);
youradapter.notifyDataSetChanged();
after that now come to the adapter class where you can set the selected textview as you want do like this
in getView method do this
if(list.get(position).getIsChecked()){
change your textview
}else{
leave as it is
}
done let me know if it helps you
Pass View in Async Task and then convert into textView and SetText in DoInBackground Method.
new PushTask().execute(v);
#Override
protected Integer doInBackground(final View position) {
runOnUiThread(new Runnable() {
public void run() {
// some code #3 (Write your code here to run in UI thread)
TextView txtName=(TextView)position;
txtname.setText(“android”):
}
});
}

Closed or circular Vertical ListView Android

I have an Vertical listview i want listview should be closed. For example if the last item is reached in Listview then show the first item below the last item. It means item should be in circular format. And if i scroll from first item it should show last item before first item. I want scrolling for both side.
public class MainActivity extends Activity {
ListView list;
long startTime;
long endTime;
List<String> mList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
downloadDetails();
String str;
for (int i = 0; i < 10; i++) {
str = new String("Data --- " + i);
mList.add(str);
}
CircularAdapter adapter = new CircularAdapter(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;
}
#SuppressLint("NewApi")
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(3000);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();// putting thread in wait
// list of mPauseLock
// object
} catch (InterruptedException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// to pause list
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
// 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 CircularAdapter extends ArrayAdapter {
List<String> mlist;
Context mContext;
LayoutInflater inflater;
public final int HALF_MAX_VALUE = Integer.MAX_VALUE / 2;
public final int MIDDLE;
#SuppressWarnings("unchecked")
public CircularAdapter(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) {
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;
}
}

Categories

Resources