I've created ProgressBar in my view, and I would like it to animate when it's value is updated. I'm runnig the code on API 23. How to animate progressBar when It's value is updated?
Here is my activity:
package com.brylkowski.cleaner.cleaner.Errands;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;
import com.brylkowski.cleaner.cleaner.R;
public class UploadErrandActivity extends AppCompatActivity {
public static final String PROGRESS = "progress";
UploadRequestTask task;
private ProgressBar progressBar;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_errand);
progressBar = (ProgressBar) findViewById(R.id.upload_progress);
progressBar.setMax(6);
task = new UploadRequestTask();
handler = new Handler() {
public void handleMessage(android.os.Message msg) {
progressBar.incrementProgressBy(1);
}
};
task.execute();
}
public class UploadRequestTask extends AsyncTask<Void, Void, Boolean> {
UploadRequestTask() {
}
#Override
protected Boolean doInBackground(Void... params) {
for (int i = 1; i <=6; i++){
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt(PROGRESS, i);
msg.setData(bundle);
handler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
}
and my view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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: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"
android:gravity="center"
tools:context="com.brylkowski.cleaner.cleaner.Errands.UploadErrandActivity">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:indeterminate="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/upload_progress"
android:layout_gravity="bottom"
android:longClickable="false"/>
</LinearLayout>
Check this for how to make ProgressBar animation. The only modification you need is instead of applying the animation once when view is initialized, you will need to call
ProgressBarAnimation anim = new ProgressBarAnimation(progressBar, progressBar.getProgress(), to);
anim.setDuration(1000);
progressBar.startAnimation(anim); // play animation immediately
every time you want to update value. Here is documentation for view animation.
Related
I want to have Horizontal progress bar that moves from 0 to 100. I added this code in layout. what should i do for moving this progress bar?
<ProgressBar
android:id="#+id/progressBar"
android:indeterminate="false"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:progress="0"
android:max="100"
style="#android:style/Widget.ProgressBar.Horizontal"
/>
Try this code :
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btn;
private ProgressBar progressBar;
TextView txt;
Integer count =1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
btn = (Button) findViewById(R.id.btn);
btn.setText("Start");
txt = (TextView) findViewById(R.id.output);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count =1;
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
new MyTask().execute(100);
});
}
class MyTask extends AsyncTask<Integer, Integer, String> {
#Override
protected String doInBackground(Integer... params) {
for (count=1 ; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
txt.setText(result);
btn.setText("Restart");
}
#Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
#Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setProgress(values[0]);
}
}
}
android:indeterminate: false
You must add the feature.
Sample
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center"
>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="116dp"
android:text="Do some stuff" />
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:id="#+id/progressBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:progress="0"/>
</LinearLayout>
class MainActivity : AppCompatActivity() {
private var progressBarStatus = 0
var dummy:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the references from layout file
var btnStartProgress = this.button1
var progressBar = this.progressBar1
// when button is clicked, start the task
btnStartProgress.setOnClickListener { v ->
// task is run on a thread
Thread(Runnable {
// dummy thread mimicking some operation whose progress can be tracked
while (progressBarStatus < 100) {
// performing some dummy operation
try {
dummy = dummy+25
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
// tracking progress
progressBarStatus = dummy
// Updating the progress bar
progressBar.progress = progressBarStatus
}
}).start()
}
}
}
I am rolling a dice and using a random function i am counting the no. of 1s,2s,3s,4s,5s,6s and printing it out .If it takes too much time then it will show a progress bar.Why my android code is not showing progress bar although i have used progress bar in my java code?
Plz figure out the mistakes.
Java Code
package dead.asynctaskprogressbar;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
editText=(EditText)findViewById(R.id.editText);
}
public class Asynctask extends AsyncTask<Integer,Integer,String>{
ProgressBar bar;
#Override
protected void onPreExecute() {
super.onPreExecute();
bar=new ProgressBar(MainActivity.this,null,android.R.attr.progressBarStyleHorizontal);
bar.setVisibility(View.VISIBLE);
bar.setMax(Integer.parseInt(editText.getText().toString().trim()));
}
#Override
protected String doInBackground(Integer... integers) {
Random random=new Random();
int ones=0,twos=0,threes=0,fours=0,fives=0,sixes=0,a;
double currentProgress=0;
double previousprogress=0;
for (int i=0;i<integers[0];i++){
currentProgress=(double)i/integers[0];
if (currentProgress-previousprogress>=0.02){
previousprogress=currentProgress;
publishProgress(i);
}
a= random.nextInt(6)+1;
switch (a){
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
default:
sixes++;
}
}
String results="Ones :"+ones +"\n"+"Twos :"+twos +"\n"+"Threes :"+threes +"\n"+"Fours :"+fours +"\n"+"Fives :"+fives +"\n"+"Sixes :"+sixes +"\n";
return results;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
bar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
public void Dice(View view){
int not=Integer.parseInt(editText.getText().toString().trim());
new Asynctask().execute(not);
}
}
Xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="dead.asynctaskprogressbar.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:hint="Dice"
android:inputType="textPersonName"
android:padding="10dp" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Dice"
android:text="Roll Dice" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20dp" />
</LinearLayout>
Why my android code is not showing progress bar
You have created ProgressBar dynamically but You didn't add that ProgressBar inside your layout that's why its not displaying
You need to add that ProgressBar in your layout
Try below code it will work fine
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
ProgressBar bar;
LinearLayout rootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar=new ProgressBar(MainActivity.this,null,android.R.attr.progressBarStyleHorizontal);
rootView=findViewById(R.id.rootView);
rootView.addView(bar);
bar.setVisibility(View.GONE);
}
public class Asynctask extends AsyncTask<Integer,Integer,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(View.VISIBLE);
bar.setMax(Integer.parseInt(editText.getText().toString().trim()));
}
#Override
protected String doInBackground(Integer... integers) {
Random random=new Random();
int ones=0,twos=0,threes=0,fours=0,fives=0,sixes=0,a;
double currentProgress=0;
double previousprogress=0;
for (int i=0;i<integers[0];i++){
currentProgress=(double)i/integers[0];
if (currentProgress-previousprogress>=0.02){
previousprogress=currentProgress;
publishProgress(i);
}
a= random.nextInt(6)+1;
switch (a){
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
default:
sixes++;
}
}
String results="Ones :"+ones +"\n"+"Twos :"+twos +"\n"+"Threes :"+threes +"\n"+"Fours :"+fours +"\n"+"Fives :"+fives +"\n"+"Sixes :"+sixes +"\n";
return results;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
bar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
public void Dice(View view){
int not=Integer.parseInt(editText.getText().toString().trim());
new Asynctask().execute(not);
}
}
Basically i want to create translate animation but for some reason i cannot use TranslateAnimation class. Anyway this is my code
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
MainActivity.java
package com.test2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ImageView;
public class MainActivity extends Activity
{
private RelativeLayout layout;
private ImageView image;
private LayoutParams imageParams;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (RelativeLayout) findViewById(R.id.layout);
image = (ImageView) findViewById(R.id.image);
imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
image.setLayoutParams(imageParams);
layout.setOnClickListener(new ClickHandler());
}
class ClickHandler implements OnClickListener
{
public void onClick(View view)
{
// This is the animation part
for (int i = 0; i < 100; i++)
{
imageParams.leftMargin = i;
image.setLayoutParams(imageParams);
// repaint() in java
try
{
Thread.sleep(100);
}
catch (Exception e)
{
}
}
}
}
}
My problem is I need to do repaint() before using Thread.sleep otherwise the animation will not work and the object will just move to its final position. I've tried invalidate, requestLayout, requestDrawableState but none works. Any suggestion?
EDIT:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity
{
private RelativeLayout layout;
private ImageView image;
private LayoutParams imageParams;
private Timer timer;
private int i;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (RelativeLayout) findViewById(R.id.layout);
image = new ImageView(this);
image.setImageResource(R.drawable.ic_launcher);
imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
image.setLayoutParams(imageParams);
layout.addView(image);
i = 0;
timer = new Timer();
runOnUiThread
(
new Runnable()
{
public void run()
{
timer.scheduleAtFixedRate
(
new TimerTask()
{
#Override
public void run()
{
imageParams.leftMargin = i;
image.setLayoutParams(imageParams);
i++;
if (i == 15)
{
timer.cancel();
timer.purge();
}
}
}, 0, 100
);
}
}
);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
</RelativeLayout>
package com.example.example;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.app.Activity;
public class MainActivity extends Activity {
ImageView imageView;
RelativeLayout.LayoutParams params;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=new ImageView(this);
RelativeLayout main=(RelativeLayout)findViewById(R.id.main);
params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
imageView.setBackgroundResource(R.drawable.ic_launcher);
imageView.setLayoutParams(params);
main.addView(imageView);
final Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
params.leftMargin=i;
imageView.setLayoutParams(params);
i++;
if(i>=100){
timer.cancel();
timer.purge();
}
}
});
}
}, 0, 100);
}
}
you can use timer task instead of sleep
Like:-
int i=0;
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
imageParams.leftMargin = i;
image.setLayoutParams(imageParams);
i++;
if(i==100){
timer.cancel();
timer.purge();
}
}
}, 0, 1000);
i have imageview and i have to display different image in
that with time interval, but when i change the ImageResource
the last image is displayed
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test);
try {
Thread.sleep(2000) ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);
}
Kindly Suggest the Right way to do that
Thanks in Advance
Perhaps this thread is what you are looking for:
how to change images with timer
Whenever you want to update the user interface without performing any action or event, handlers should be used.
This is the sample code
Main.java
package com.balaji.handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;
public class Main extends Activity {
private ImageView txtStatus;
int i=0;
int imgid[]={R.drawable.icon,R.drawable.back,R.drawable.slider,R.drawable.forward};
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Main.this.updateUI();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
private void updateUI(){
//int currentInt = Integer.parseInt((String) txtStatus.getText()) + 10;
if(i<imgid.length){
mRedrawHandler.sleep(1000);
txtStatus.setBackgroundResource(imgid[i]);
i++;
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
this.txtStatus = (ImageView)this.findViewById(R.id.txtStatus);
updateUI();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
</ImageView>
</RelativeLayout>
Here's my error:
*** Uncaught remote exception! (Exceptions are not yet supported across processes.)
android.util.AndroidRuntimeException: { what=1008 when=368280372 } This message is already in use.
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:171)
at android.os.Handler.sendMessageAtTime(Handler.java:457)
at android.os.Handler.sendMessageDelayed(Handler.java:430)
at android.os.Handler.sendMessage(Handler.java:367)
at android.view.ViewRoot.dispatchAppVisibility(ViewRoot.java:2748)
What I'm attempting is to have a listview, that is populated by custom list items, each list item has multiple views and each view has an onclick listener attached. When this onClickListener is pressed it sends a Message to a Handler with a what and arg1 arguments.
Clicking one of my elements fires an intent to start a new activity.
Clicking the other shows a toast.
When these are pressed in a combination I get the error above. Namely clicking the text to fire the intent, (then press back) then clicking the image to show the toast, then when you click the text to fire the intent again I get the FC.
And here is the code below, I tried to remove as much cruft as I could to get to the bones of the error:
If you want to skip to whats important look at the onClickListener's in ConversationAdapter.class and how they interact with StartPage.class
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.handler.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".StartPage"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DetailsPage"
android:label="DetailsPage"
>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
StartPage.class:
package com.handler.test;
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class StartPage extends ListActivity {
private ArrayList<Conversation> mConversations = null;
private ConversationAdapter mAdapter;
private Context mContext;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
mConversations = new ArrayList<Conversation>();
this.mAdapter = new ConversationAdapter(mContext, R.layout.inbox_row, mConversations, mHandler);
setListAdapter(this.mAdapter);
new Thread(new Runnable() {
#Override
public void run() {
getConversations();
}
}).start();
mProgressDialog = ProgressDialog.show(StartPage.this, "Please wait...", "Retrieving data ...", true);
}
private void getConversations() {
try {
mConversations = new ArrayList<Conversation>();
Conversation o1 = new Conversation();
o1.setStatus("SF services");
o1.setMessage("Pending");
mConversations.add(o1);
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(mConversations != null && mConversations.size() > 0){
mAdapter.notifyDataSetChanged();
for(int i=0;i<mConversations.size();i++)
mAdapter.add(mConversations.get(i));
}
mProgressDialog.dismiss();
mAdapter.notifyDataSetChanged();
}
};
private Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
int convIndex = msg.arg1;
int viewTouched = msg.what;
switch(viewTouched){
case ConversationAdapter.PROF_ICON:
showNumber(convIndex);
break;
case ConversationAdapter.MESSAGE:
showMessageDetails(convIndex);
break;
}
super.handleMessage(msg);
}
};
private void showNumber(int convIndex) {
Toast.makeText(mContext, "Pressed: "+convIndex, Toast.LENGTH_LONG).show();
}
private void showMessageDetails(int convIndex) {
final Conversation conv = mConversations.get(convIndex);
Intent i = new Intent(mContext, DetailsPage.class);
i.putExtra("someExtra", conv);
startActivity(i);
}
}
DetailsPage.class
package com.handler.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class DetailsPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Test", "Details Page");
}
}
Conversation.class:
package com.handler.test;
import java.io.Serializable;
public class Conversation implements Serializable {
private static final long serialVersionUID = -437261671361122258L;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
ConversationAdapter.class:
package com.handler.test;
import java.util.ArrayList;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ConversationAdapter extends ArrayAdapter<Conversation> {
public static final int PROF_ICON = 0;
public static final int MESSAGE = 1;
private Context mContext;
private Handler mHandler;
private ArrayList<Conversation> mItems;
private int mXmlId;
private LinearLayout detailsOfConv;
private ImageView iconImage;
public ConversationAdapter(Context context, int textViewResourceId, ArrayList<Conversation> items, Handler handler) {
super(context, textViewResourceId, items);
this.mContext = context;
this.mItems = items;
this.mXmlId = textViewResourceId;
this.mHandler = handler;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mXmlId, null);
}
final Message m = new Message();
m.arg1 = position;
Conversation c = mItems.get(position);
if (c != null) {
iconImage = (ImageView) v.findViewById(R.id.icon);
if (iconImage != null) {
iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.what = PROF_ICON;
mHandler.sendMessage(m);
}
});
}
detailsOfConv = (LinearLayout) v.findViewById(R.id.details);
if(detailsOfConv != null){
detailsOfConv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.what = MESSAGE;
mHandler.sendMessage(m);
}
});
}
}
return v;
}
}
main.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"
android:padding="10dip"
>
<ListView
android:id="#+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
/>
</LinearLayout>
inbox_row.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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="6dip"
android:src="#drawable/icon" />
<LinearLayout
android:id="#+id/details"
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/toptext"
android:textColor="#99FF66"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:text="123456789"
/>
</LinearLayout>
</LinearLayout>
My guess would be that you are sending twice the same message. Indeed in the code there is one new Message() and two mHandler.sendMessage(m) which are possibly both executed.
Try making a new message for every time you send a message.
Edited:
Message.obtain() is preferable to Message m = new Message() (because it recycles used messages under the hood)
In your case you could use new.copyFrom(old) if you need a copy of existing message.