I have two images in my drawable folder and I desire to alternate the two images in my view every x time.
I try to use a Asynctask but don't work and I can't found the solution.
My xml Code
<ImageView
android:id="#+id/imageload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="64dp"
android:adjustViewBounds="false"
android:baselineAlignBottom="false"
android:contentDescription="#string/imatge"
android:cropToPadding="false"
android:fitsSystemWindows="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/hdtitol2" />
I call the class with:
new ModifyImage().execute(null,null,null);
The main class contains de class with async code
public class ModifyImage extends AsyncTask<Void, Void, Void> {
ImageView img= (ImageView)findViewById(R.id.imageload);
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int i = 0;
boolean opt = true;
boolean exit = false;
while(!exit){
if(i == 1000){
i = 0;
if(!opt){
img.setImageResource(R.drawable.blackhdtitol2);
opt =true;
}else{
opt = false;
img.setImageResource(R.drawable.hdtitol2);
}
}
i++;
}
return null;
}
#Override
protected void onPostExecute(Void i){
}
}
Do this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Integer tag = (Integer) img.getTag();
if(tag == R.drawable.blackhdtitol2){
img.setImageResource(R.drawable.blackhdtitol2);
img.setTag(R.drawable.blackhdtitol2);
}else{
img.setImageResource(R.drawable.hdtitol2);
img.setTag(R.drawable.hdtitol2);
}
}
}, 60*1000);
In the end I found a possible solution descarting all de java code that I had about this problem.
The solution that I found is to create a new class
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
public RepeatingThread() {
}
#Override
public void run() {
final ImageView img = (ImageView) findViewById(R.id.imageload);
if(img.getVisibility() == View.INVISIBLE ){
img.setVisibility(View.VISIBLE);
}else{
img.setVisibility(View.INVISIBLE);
}
mHandler.postDelayed(this, 1000);
}
}
And the code in the function on create:
final Thread t = new Thread(new RepeatingThread());
t.start();
Related
Goal: To have a connect icon in the action bar. OnClick, it should try to connect in the background. While it is trying to connect, the connection animation should play. It should then switch back to "not_connected" or "connected" drawable, depending on success or failure.
Problem: If I call the code inside the onClick method of the Custom Action Provider, it works perfectly (see commented-out portion that toggles it). When the same exact code is inside onPreExecute of the AsyncTask, it will not play (it stays on the first frame), even though I am passing a reference to the ImageView.
My setup: To do a Frame Animation in the action bar, you have to use a Custom Action Provider (see animationDrawable is not playing in Actionbar?). So, I have a custom layout, a Custom Action Provider that inflates it and sets up the on-click method. My connection functionality is inside an AsyncTask so that it will connect asynchronously.
Any ideas?
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/connect"
android:showAsAction="always"
android:title="#string/btn_connect"
android:actionProviderClass="com.****.ConnectIconActionProvider"
/>
</menu>
layout/connecting_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ivConnecting"
style="#android:style/Widget.ActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_not_connected" />
anim/connectinganimation.xml
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="#drawable/ic_connecting1" android:duration="300" />
<item android:drawable="#drawable/ic_connecting2" android:duration="300" />
<item android:drawable="#drawable/ic_connecting3" android:duration="300" />
</animation-list>
ConnectIconActionProvider.java
public class ConnectIconActionProvider extends ActionProvider {
private Context context;
private ImageView button;
// boolean toggle = false;
private AnimationDrawable animationDrawable;
public ConnectIconActionProvider(Context context) {
super(context);
this.context = context;
}
#Override
public View onCreateActionView(MenuItem forItem) {
// Inflate the action view to be shown on the action bar.
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.connecting_animation, null);
button = (ImageView) view.findViewById(R.id.ivConnecting);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyClass.toggleConnectionToDevice(button);
// if (toggle) {
// button.setImageResource(R.anim.connectinganimation);
// animationDrawable = (AnimationDrawable) button.getDrawable();
// animationDrawable.start();
// } else {
// button.setImageResource(R.drawable.ic_not_connected);
// if (animationDrawable != null) {
// animationDrawable.stop();
// }
// }
// toggle ^= true;
}
});
return view;
}
MyClass.toggleConnectionToDevice
public void toggleConnectionToDevice(ImageView iv) {
if (deviceConnected) {
(new DisconnectProgressBar(this, iv)).execute();
} else {
(new ConnectProgressBar(this, iv)).execute();
}
}
ConnectProgressBar.java
public class ConnectProgressBar extends AsyncTask<Void, Void, Void> {
private final MainActivity activity;
private AnimationDrawable animationDrawable;
private ImageView iv;
private Handler handler = new Handler(Looper.getMainLooper());
public ConnectProgressBar(final MainActivity activity, final ImageView iv) {
this.activity = activity;
this.iv = iv;
}
#Override
protected void onPreExecute() {
if (iv != null) {
iv.setImageResource(R.anim.connectinganimation);
animationDrawable = (AnimationDrawable) iv.getDrawable();
animationDrawable.start();
}
}
#Override
protected Void doInBackground(final Void... params) {
// Connect to Car
handler.post(new Runnable() {
public void run() {
activity.isCurrentlyConnecting = true;
activity.connect();
}
});
return null;
}
#Override
protected void onPostExecute(final Void result) {
if (activity.deviceConnected) {
// Show Connected Icon
if (animationDrawable != null) {
animationDrawable.stop();
}
if (iv != null) {
iv.setImageResource(R.drawable.ic_connected);
}
} else {
Toast.makeText(activity, "Connect failed!", Toast.LENGTH_LONG).show();
// Show Disconnected Icon
if (animationDrawable != null) {
animationDrawable.stop();
}
if (iv != null) {
iv.setImageResource(R.drawable.ic_not_connected);
}
}
}
}
I ended up scrapping the custom action provider and animation xml. I am just doing it manually with a timer inside of my AsyncTask. It might not be as "correct", but it's definitely simpler.
public class ConnectProgressBar extends AsyncTask<Void, Void, Void> {
private final MainActivity activity;
private MenuItem item;
private Timer timer;
public ConnectProgressBar(final MainActivity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
startAnimation();
}
#Override
protected Void doInBackground(final Void... params) {
// Connect to Car
activity.connectHardware();
return null;
}
#Override
protected void onPostExecute(final Void result) {
stopAnimation();
if (myClass.deviceConnected) {
// Show Connected Icon
if (item != null) {
setIcon(R.drawable.ic_connected);
setTitle(R.string.btn_disconnect);
}
} else {
Toast.makeText(activity, "Connect failed!", Toast.LENGTH_LONG).show();
// Show Disconnected Icon
if (item != null) {
setIcon(R.drawable.ic_not_connected);
setTitle(R.string.btn_connect);
}
}
}
private void startAnimation() {
if (timer == null) {
timer = new Timer();
}
timer.schedule(new AnimateTask(), 0, 300);
}
private class AnimateTask extends TimerTask {
int frame = 0;
AnimateTask() {
if (item == null) {
item = activity.myMenu.findItem(R.id.connect);
}
if (item != null) {
setTitle(R.string.btn_connecting);
}
}
#Override
public void run() {
// Animate!
switch (frame % 3) {
case 0:
setIcon(R.drawable.ic_connecting1);
break;
case 1:
setIcon(R.drawable.ic_connecting2);
break;
case 2:
setIcon(R.drawable.ic_connecting3);
break;
}
frame++;
}
}
private void setIcon(final int resId) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
item.setIcon(resId);
}
});
}
private void setTitle(final int resId) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
item.setTitle(resId);
}
});
}
private void stopAnimation() {
timer.cancel();
timer = null;
}
}
I figured out the issue with my initial block of code. The handler is running on the UI thread, so it blocks the UI thread from updating.
private Handler handler = new Handler(Looper.getMainLooper());
protected Void doInBackground(final Void... params) {
handler.post(new Runnable() {
public void run() {
activity.isCurrentlyConnecting = true;
activity.connect();
}
});
return null;
}
I am using ImageDownloader class to get images from server and getting these images links using an ArrayList. After downloading the Image I am setting the Image as background of the layout. All is working but I want to change these Images after a specific time interval and set as background different images. I have gone through many posts here but didn't get what I want. As I have all Images links in ArrayList, so how can I set a timer to change the images, coming from that ArrayList.It always show me the first Image at index zero even I have set a timer but the same Image is showing again? Please help me if someone has any code example and see my code what to change there?
final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
for(int i=0; i<list.size(); i++)
{
item = list.get(i);
}
downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage);
I do not know about ImageLoader component but scheduling a timer on a view is quite easy in Android.(Without any additional Object)
final ImageView bgImage=(ImageView) findViewById(R.id.image);
...
new Runnable() {
int updateInterval = 1000; //=one second
#Override
public void run() {
// Any code which goes here will be executed every 'updateInterval'
// change your background here
bgImage.postDelayed(this, updateInterval);
}
}.run();
You can change this template as you wish, suppose I want to stop this timer, for this purpose I have to add a stop method to my runnable(This stop method acts synchronized and do not cause inconsistency in timer inner codes):
Runnable myRunnable = new Runnable() {
int updateInterval = 1000; //=one second
boolean stop = false;
public void stop() {
this.stop = true;
}
#Override
public void run() {
// Any code which goes here will be executed every 'updateInterval'
// change your background here
if(!stop) {
bgImage.postDelayed(this, updateInterval);
}
}
}.run();
Now I can stop it by myRunnable.stop();
EDIT :
You should iterate your array of URLs and pass one of them to your downloader. It can be accomplished by this snippet code:
int arraySize = list.size();
new Runnable() {
int currentIndex = 0;
int updateInterval = 1000; //=one second
#Override
public void run() {
currentIndex += 1;
if(currentIndex == arraySize){
currentIndex = 0;
}
item = list.get(currentIndex);
downloader.download(item.imageurl(), bgImage);
bgImage.postDelayed(this, updateInterval);
}
}.run();
Set up your ImageView like this:
<ImageView
android:id="#+id/imgBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY" />
You can Use TimerTask to achieve this.
// Declaration and Initialization :
List<String> mImageUrl = new ArrayList<String>();
private ImageLoader mImageLoader = new ImageLoader(MainActivity.this);
Timer timer = new Timer(); // changed
int i = 0;
// Put this code in your onCreate :
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (i < mImageUrl.size()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mImageLoader.DisplayImage(mImageUrl.get(i), img);
i++;
}
});
} else {
i = 0;
}
}
}, 0, 2000);
The timer task will start in 0 seconds and it will change the background every 2 seconds. You can change this as like as you want.
Its working fine. I have tested.
You can read more about the timertask here.
You can also cancel the timer with the help of timer.cancel() HIH.
final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
for(int i=0; i<list.size(); i++)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
item = list.get(i);
downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage)
}
});
}
Try this way hope this will help you for more improvement of your code...
you need "Aquery(AndroidQuery)" jar from this reference :
https://code.google.com/p/android-query/downloads/detail?name=android-query-full.0.24.3.jar
2.now add this jar on your project lib folder and add to build path or as library.
3.now it's time for code using "Aquery(AndroidQuery)" to download images from server(here is my demo code you can modified as per your requirement).
"activity_main.xml"
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgFromServer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="#+id/pbrImageLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
"MyActivity.java"
public class MyActivity extends Activity{
private ImageView imgFromServer;
private ProgressBar pbrImageLoader;
private AQuery aQuery;
private int currentIndex;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgFromServer = (ImageView) findViewById(R.id.imgFromServer);
pbrImageLoader = (ProgressBar) findViewById(R.id.pbrImageLoader);
aQuery = new AQuery(this);
currentIndex=0;
final ArrayList<String> imageUrlListFromServer = new ArrayList<String>();
imageUrlListFromServer.add("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
imageUrlListFromServer.add("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
imageUrlListFromServer.add("http://www.hdwallshub.com/files/submissions/cookie_monster_hd_wallpaper_1405239014.jpg");
imageUrlListFromServer.add("http://images4.fanpop.com/image/photos/17200000/Tangled-offical-wallpapers-tangled-17286338-1680-1050.jpg");
imageUrlListFromServer.add("http://wakpaper.com/large/Moons_wallpapers_4.jpg");
final Timer timer = new Timer();
downloadImagesFromServer(imageUrlListFromServer, 0, new ImageDownloadedListener() {
#Override
public void onDownloadFinish() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
imgFromServer.setImageBitmap(aQuery.getCachedImage(imageUrlListFromServer.get(currentIndex)));
if(currentIndex == imageUrlListFromServer.size()-1){
currentIndex=0;
}else{
currentIndex++;
}
}
});
}
},0,2000);
}
});
}
private void downloadImagesFromServer(final ArrayList<String> imageUrlList,final int index,final ImageDownloadedListener listener){
aQuery.progress(pbrImageLoader).ajax(imageUrlList.get(index), Bitmap.class, 0, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
if ((imageUrlList.size() - 1) == index) {
listener.onDownloadFinish();
} else {
downloadImagesFromServer(imageUrlList, index + 1, listener);
}
}
});
}
interface ImageDownloadedListener{
public void onDownloadFinish();
}
}
Note : "Aquery(AndroidQuery)" also cache images on local so it not get same images from server if it already downloaded.
try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}}});}}
catch (InterruptedException e) {
}}};
}
Okay a little help here, so I have two images loading in my splash screen. The first image opens (starting the splash screen) then the second image opens, once the second image closes the mainactivity starts. Now my question is how do I make my first image fade out, then fade in with my second image?
-Oh yes, and no cross fading
-Just a complete fade out and in transition
-Thanks in advance
-The splash.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:id="#+id/lin_lay"
android:gravity="center" >
<ImageView
android:contentDescription="#string/desc"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinning_wheel_image"
android:background="#drawable/splashscreen1" />
</LinearLayout>
The mainanim.xml
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="#drawable/splashscreen1" android:duration="2500" />
<item android:drawable="#drawable/splashscreen2" android:duration="4000" />
</animation-list>
The Splash.java
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.splashsound);
ourSong.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(10500);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoint = new Intent("com.theapplication.app.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
#Override
public void setRequestedOrientation(int requestedOrientation) {
// TODO Auto-generated method stub
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
ImageView mainimage = (ImageView)findViewById(R.id.spinning_wheel_image);
mainimage.setBackgroundResource(R.anim.mainamin);
mainanimation = (AnimationDrawable) mainimage.getBackground();
mainanimation.start();
use ImageSwitcher instead of ImageView which support animations by it self.
see this sample:
http://www.java2s.com/Code/Android/UI/UsingImageSwitcher.htm
you can add animation like this:
imageSwitcher.setInAnimation(fadeInAnimation);
imageSwitcher.setOutAnimation(fadeOutAnimation);
//
my test:
public class IntroActivity extends Activity implements ViewFactory {
private static final String TAG = "IntroActivity";
private final int[] images = { R.drawable.img3, R.drawable.img2,
R.drawable.img1, R.drawable.img4, R.drawable.img5, R.drawable.img6,
R.drawable.img7, R.drawable.img8 };
private int index = 0;
private final int interval = 10000;
private boolean isRunning = true;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_intro);
startAnimatedBackground();
}
private void startAnimatedBackground() {
Animation aniIn = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
aniIn.setDuration(3000);
Animation aniOut = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
aniOut.setDuration(3000);
final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
imageSwitcher.setInAnimation(aniIn);
imageSwitcher.setOutAnimation(aniOut);
imageSwitcher.setFactory(this);
imageSwitcher.setImageResource(images[index]);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (isRunning) {
index++;
index = index % images.length;
Log.d("Intro Screen", "Change Image " + index);
imageSwitcher.setImageResource(images[index]);
handler.postDelayed(this, interval);
}
}
};
handler.postDelayed(runnable, interval);
}
#Override
public View makeView() {
ImageView imageView = new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return imageView;
}
#Override
public void finish() {
isRunning = false;
super.finish();
}
}
to start next activity, in
#Override
public void run() {
if (isRunning) {
just check for the index,
if the index equals to 1 then start the next activity and finish the current;
You can simply just fade out the image, change it, and then finally fade it in again.
imageView.animate()
.alpha(0f)
.setDuration(100)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) { }
#Override
public void onAnimationEnd(Animator animator) {
imageView.setImageResource(R.drawable.newimg);
imageView.animate().alpha(1).setDuration(200);
}
#Override
public void onAnimationCancel(Animator animator) { }
#Override
public void onAnimationRepeat(Animator animator) { }
});
Is it possible to add text from java coding of a list view to marquee scroll in Android. If yes can you please let me know how?
If needed I shall post the code used.
This was the XML for listview used is as follows
<?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="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
<ListView
android:id="#+id/audiolist_listView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:layout_weight="1"
android:background="#drawable/backgroundimg"
android:divider="#drawable/gradient"
android:dividerHeight="1dp"
android:scrollbars="vertical" >
</ListView>
</LinearLayout>
The java class for listview is as follows
public class Audiovediolist extends Activity implements OnItemClickListener {
private ListView audioList;
private Intent frmHome;
private ArrayList<HashMap<String, String>> dataList;
private HashMap<String, String> map;
private HashMap<String, String> data;
private int Screen_Id;
private AdView adView;
String name;
String mSign[] = { "Aries-Mesam", "Taurus-Vrushabham", "Gemini-Midhunam",
"Cancer-Karkatakam", "Leo-Simham", "Virgo-Kanya", "Libra-Tula",
"Scorpio-Vruchikam", "Sagittarius-Dhanussu", "Capricorn-Makaram",
"Aquarius-Kumbham", "Pisces-Meenam" };
Integer mImages[] = { R.drawable.meshamu, R.drawable.vrushabhamu,
R.drawable.medhunam, R.drawable.karkatakam, R.drawable.simham,
R.drawable.kanya, R.drawable.tula, R.drawable.vruchikam,
R.drawable.dhanussu, R.drawable.makaramu, R.drawable.kumbhamu,
R.drawable.meenamu };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.list);
frmHome = getIntent();
getIntentValues();
initUI();
setUI();
uiListener();
}
private void initUI() {
audioList = (ListView) findViewById(R.id.audiolist_listView);
dataList = new ArrayList<HashMap<String, String>>();
adView = new AdView(this, AdSize.SMART_BANNER, "a150b89c23af3b2");
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
layout.setGravity(Gravity.TOP);
layout.addView(adView);
adView.loadAd(new AdRequest());
}
private void uiListener() {
audioList.setOnItemClickListener(this);
}
private void getIntentValues() {
String id = frmHome.getStringExtra("Activity_Id");
Screen_Id = Integer.parseInt(id);
if (Screen_Id == 1) {
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.audioo);
this.setTitle(getResources().getString(R.string.audio));
this.setTitleColor(getResources().getColor(R.color.Beige));
} else {
this.setTitle(getResources().getString(R.string.video));
this.setTitleColor(getResources().getColor(R.color.Beige));
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.videoo);
}
}
private void setAdapter() {
SimpleAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_row, new String[] { "Image", "text" }, new int[] {
R.id.audiolist_row_img, R.id.audiolist_row_tv });
audioList.setAdapter(adapter);
}
private void setUI() {
for (int a = 0; a <= 11; a++) {
map = new HashMap<String, String>();
map.put("Image", "" + mImages[a]);
map.put("text", mSign[a]);
dataList.add(map);
map = null;
}
}
#Override
protected void onStart() {
super.onStart();
setAdapter();
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
/*
* private class NextTask extends AsyncTask<Void,Void,Void> { ProgressDialog
* progressDailog = new ProgressDialog(Audiovediolist.this);
*
* #Override protected void onPreExecute() { super.onPreExecute();
* progressDailog.setTitle("Please Wait");
* progressDailog.setMessage("URL Data Loading ...");
* progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
* progressDailog.setCancelable(true); progressDailog.show(); }
*
* #SuppressWarnings("static-access")
*
* #Override protected Void doInBackground(Void... params) { return null; }
*
* #Override protected void onPostExecute(Void result) {
* progressDailog.dismiss(); } }
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
data = dataList.get(position);
//FinalConstants.AUDIO_VIDEO = "list";
try {
NetWorkCheck netWork = new NetWorkCheck();
if (netWork.isNetWorkConnection(this)) {
if (Screen_Id == 1) {
// new NextTask().execute();
Intent audioInt=new Intent(getApplicationContext(),AudioView.class);
audioInt.setType(data.get("text"));
startActivity(audioInt);
} else if (Screen_Id == 2) {
Intent vedioInt = new Intent(this, VideoPlayActivity.class);
vedioInt.setType(data.get("text"));
startActivity(vedioInt);
}
} else {
netWork.alert();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Problem while ListItemClick",
Toast.LENGTH_SHORT).show();
}
}
}
The code for audio player where i need the text selected to scroll is as follows
public class AudioView extends Activity implements OnClickListener {
private MediaPlayer mMediaPlayer;
private ImageView mPlay;
private ImageView mPause;
private ImageView mBack;
private ImageView mFar;
private ProgressBar myProgressBar;
private boolean boolFlag = false;
private boolean isPausedInCall = false;
private String url;
private TelephonyManager mTelephoneMgr;
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
private TextView tv;
// private boolean serviceRunning;
Notification notifyDetails;
private AdView adView;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.marquee);
Toast.makeText(this,"please wait.........",Toast.LENGTH_LONG).show();
url=getIntent().getType();
initUI();
uiListener();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notifyDetails = new Notification(R.drawable.mulug_icon, url,
System.currentTimeMillis());
mTelephoneMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mTelephoneMgr != null) {
mTelephoneMgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/*if(FinalConstants.AUDIO_VIDEO=="listitem"){
LoginProgress task = new LoginProgress();
task.applicationContext = AudioView.this;
task.execute();
}*/
}
private void initUI() {
tv = (TextView) findViewById(R.id.text);
mBack = (ImageView) findViewById(R.id.back);
mPlay = (ImageView) findViewById(R.id.play);
mPause = (ImageView) findViewById(R.id.pause);
mFar = (ImageView) findViewById(R.id.fwd);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
myProgressBar.setProgressDrawable(getResources().getDrawable(
R.drawable.green_progress));
myProgressBar.setProgress(0);
adView = new AdView(this, AdSize.BANNER, "a150b89c23af3b2");
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
layout.setGravity(Gravity.TOP);
layout.addView(adView);
adView.loadAd(new AdRequest());
tv.setText(url + "more Deails Click on www.mulugu.com");
tv.setSelected(true);
}
private void uiListener() {
mPlay.setOnClickListener(this);
mPlay.setOnClickListener(this);
mPause.setOnClickListener(this);
mPause.setVisibility(android.view.View.INVISIBLE);
mBack.setOnClickListener(this);
mFar.setOnClickListener(this);
}
private Thread myThread = new Thread() {
public void run() {
while (mMediaPlayer.getCurrentPosition() < mMediaPlayer
.getDuration()) {
try {
myProgressBar
.setProgress(mMediaPlayer.getCurrentPosition());
} catch (Throwable t) {
}
}
}
};
#Override
protected void onStart() {
super.onStart();
this.setProgressBarIndeterminateVisibility(true);
try {
if (boolFlag == false) {
System.out.println(FinalConstants.URL + "mobile-audio/" + url+ ".mp3");
mMediaPlayer = MediaPlayer.create(
this,
Uri.parse(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3"));
}
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Data not available",
Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "Data Not Exist in that Url...");
super.onBackPressed();
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#Override
public void onBackPressed() {
super.onBackPressed();
mMediaPlayer.stop();
// myThread.stop();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
System.gc();
}
#Override
protected void onDestroy() {
adView.destroy();
super.onDestroy();
System.gc();
}
public PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
System.out.println("ringing state");
if (mMediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
notificationShow();
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
System.out.println("callState Idle");
if (mMediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
private void pauseMedia() {
mMediaPlayer.pause();
changePlayerIcons(false);
}
private void playMedia() {
mMediaPlayer.start();
changePlayerIcons(true);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!boolFlag) {
try {
notificationShow();
mMediaPlayer.setLooping(false);
mMediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "preparing", Toast.LENGTH_SHORT)
.show();
}
boolFlag = true;
mMediaPlayer.start();
myThread.start();
} else {
notificationShow();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.start();
}
changePlayerIcons(true);
myProgressBar.setProgress(mMediaPlayer.getCurrentPosition());
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
changePlayerIcons(false);
myProgressBar.setProgress(0);
onStart();
}
});
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
break;
case R.id.pause:
mMediaPlayer.pause();
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
break;
case R.id.back:
int dur = mMediaPlayer.getCurrentPosition();
int pos = (dur > 10000 ? dur - 5000 : 0);
mMediaPlayer.seekTo(pos);
break;
case R.id.fwd:
int curpos = mMediaPlayer.getCurrentPosition();
int dur2 = mMediaPlayer.getDuration();
int pos2 = (curpos + 5000 > dur2 ? dur2 : curpos + 5000);
mMediaPlayer.seekTo(pos2);
break;
}
}
#SuppressWarnings("deprecation")
private void notificationShow() {
Context context = getApplicationContext();
CharSequence contentTitle = "Mulugu Running";
CharSequence contentText = url + " Weekly Predictions";
Intent notifyIntent = new Intent(AudioView.this, AudioView.class);
PendingIntent intent = PendingIntent.getActivity(AudioView.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText,
intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
private void changePlayerIcons(boolean b) {
if (b) {
mPlay.setVisibility(android.view.View.INVISIBLE);
mPause.setVisibility(android.view.View.VISIBLE);
} else {
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
}
}
/*public class LoginProgress extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.dialog.dismiss();
}
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Data Loading",
"Loading .....", true);
}
#Override
protected Void doInBackground(Void... params) {
LoadUrl();
return null;
}
private void LoadUrl() {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.reset();
try {
mMediaPlayer.setDataSource(AudioView.this,Uri.parse(FinalConstants.URL + "mobile-audio/" + getIntent().getType()+ ".mp3"));
mMediaPlayer.setLooping(false); // Set looping
mMediaPlayer.prepare();
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
e.printStackTrace();
}
}
}*/
}
If you need to move text around, maybe this will help:
http://developer.android.com/guide/topics/resources/animation-resource.html#translate-element
If you have a TextView with a text that is too big and you want it to move around so people can read the whole thing, try android:ellipsize="marquee" in the .xml file, or in the Java code:
textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
If the android libraries not enough, you can always use the java via coding. Create a thread class that gets the views and change conditions over time. You can create an intent to call that class.
You can use the TextSwitcher and apply the animation on it.
Try below code:
public class TextSwitcherActivity extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener
{
private TextSwitcher m_switcher;
private Button m_nextButton;
private int m_counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_switcher = (TextSwitcher) findViewById(R.id.tsSwitcher);
m_switcher.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
m_switcher.setInAnimation(in);
m_switcher.setOutAnimation(out);
m_nextButton = (Button) findViewById(R.id.next);
m_nextButton.setOnClickListener(this);
updateCounter();
}
/**
* Update counter value
*/
public void onClick(View v)
{
m_counter++;
updateCounter();
}
/**
* Set text on textswitcher
*/
private void updateCounter()
{
m_switcher.setText(String.valueOf(m_counter));
}
public View makeView()
{
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
You can define your own animations to get the marquee effect.
Here is the example
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/mywidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textColor="#ff4500"
android:text="Simple application that shows how to use marquee, with a long text" />
In java (If you are using a Listview and binding an adapter, then in getview when u inflate Layout and its view component, set the selected flag to true to your TextView.)
tv = (TextView) this.findViewById(R.id.tv);
tv.setSelected(true);
By using below method you can convert your list of string values into a single string,
String listString = String.join(", ", list);
This will convert list values into string and with that you can achieve this. I know this is very late but I posted because there is no solution provided that's why.
I'm just trying to test some stuff with a splash screen. The strangest thing happens when I run the app though. I can see my Log messages in the LogCat, but the activity itself won't show up. Once the loop finishes, it starts the next activity, which does in fact show up. If I comment out the UIThread, it will show up though. I know I'm doing something simple wrong, but I'm not sure what it is. Ideas?
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<ImageView
android:id="#+id/logoIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="50dp"
android:paddingTop="50dp"
android:src="#drawable/logoa"
/>
Java:
public class Splash extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
final ImageView logo = (ImageView) findViewById(R.id.logoIV);
final int[] anim = new int[6];
anim[0]=R.drawable.logoa;
anim[1]=R.drawable.logob;
anim[2]=R.drawable.logoc;
anim[3]=R.drawable.logod;
anim[4]=R.drawable.logoe;
anim[5]=R.drawable.logof;
runOnUiThread(new Runnable() {
int img = 0, counter=0;
boolean up = true;
public void run() {
while(counter<21){
logo.setImageResource(anim[img]);
if(up){
img++;
if(img>=5)
up=false;
}else{
img--;
if(img<=0)
up=true;
}
try{
Thread.sleep(150);
}catch (InterruptedException e){
e.printStackTrace();
}
counter++;
Log.e("Tag",Integer.toString(counter));
}
if(counter>=21){
Intent creditsIntent = new Intent(Splash.this, TitlePage.class);
creditsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Splash.this.startActivity(creditsIntent);
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
change your oncreate method like this
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
final ImageView logo = (ImageView) findViewById(R.id.logoIV);
final int[] anim = new int[6];
anim[0] = R.drawable.logoa;
anim[1] = R.drawable.logob;
anim[2] = R.drawable.logoc;
anim[3] = R.drawable.logod;
anim[4] = R.drawable.logoe;
anim[5] = R.drawable.logof;
Thread t = new Thread(new Runnable()
{
int img = 0, counter = 0;
boolean up = true;
#Override
public void run()
{
while (counter < 21)
{
runOnUiThread(new Runnable()
{
public void run()
{
logo.setImageResource(anim[img]);
}
});
if (up)
{
img++;
if (img >= 5)
up = false;
}
else
{
img--;
if (img <= 0)
up = true;
}
try
{
Thread.sleep(150);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
counter++;
Log.e("Tag", Integer.toString(counter));
}
if (counter >= 21)
{
runOnUiThread(new Runnable()
{
public void run()
{
Intent creditsIntent = new Intent(Splash.this, TitlePage.class);
creditsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Splash.this.startActivity(creditsIntent);
}
});
}
}
});
t.start();
}
instead of calling runOnUiThread directly do the following:
new Timer().schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
int img = 0, counter=0;
.....
}
}
}, 1000);
I'm not sure if your animation will work, but surely your activity will show up.