Image is not changing in ImageView - java

I want to change image after some animation to first image. I am trying with this code but only the second image is getting animated. First image is not displaying.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anim();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void anim() {
Animation animfadein =AnimationUtils.loadAnimation(this,R.anim.fadein);
Animation animfadeout =AnimationUtils.loadAnimation(this,R.anim.fadeout);
findViewById(R.id.imageView1).startAnimation(animfadein);
findViewById(R.id.imageView1).startAnimation(animfadeout);
Context myActivity =getApplicationContext();
Toast.makeText(myActivity, "Please wait", Toast.LENGTH_SHORT).show();
button();
}
public void button() {
ImageView imgView1 = (ImageView)findViewById(R.id.imageView1);
Drawable myDrawable = getResources().getDrawable(R.drawable.start);
imgView1.setImageDrawable(myDrawable);
}
}
My xml file is like this
<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:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:contentDescription="#string/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_logo"/>
</LinearLayout>
I tried using setImageresource still same first image is not displaying.
Please let me know what mistake i have done.Thanks in advance :)

You are running everything in onCreate which is done before the user is even able to see any of the UI. It is until onStart that the user will see the UI. even so, the change will be almost immediate, so you might want to wait a few secs. Try this:
#Override
protected void onStart() {
super.onStart();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
anim();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
In general you are making a thread wait 5 secs then do the animation. I am not going to go over what's the best way to do this, but you certainly need to modify this on the UI thread, so I included it in the snippet.
For more information about threading go here:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

You will need to use animation listener for achieving this:
animFadeIn.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
//start animFadeOut Here
}
});
Hope this helps.

Related

ViewPropertyAnimator - animation wouldn't happen the first time

I'm using the following code for a slide in / slide out toggle for an AppBarLayout.
public void showToolbar(boolean show) {
if (appBar == null) {
Log.e(TAG, "showToolbar: Toolbar is null");
return;
}
boolean toolbarShown = Utils.isViewVisible(appBar);
Log.d(TAG, "showToolbar: shown:" +shown);
boolean changed = (show != toolbarShown);
if (changed) {
if (show) {
Log.d(TAG, "showToolbar: showing");
appBar.setVisibility(View.VISIBLE);
appBar.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
appBar.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationEnd(Animator animator) { }
#Override
public void onAnimationCancel(Animator animator) { }
#Override
public void onAnimationRepeat(Animator animator) { }
})
.start();
} else {
Log.d(TAG, "showToolbar: hiding");
appBar.animate()
.translationY(-toolbar.getBottom())
.setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) { }
#Override
public void onAnimationEnd(Animator animator) {
appBar.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationCancel(Animator animator) { }
#Override
public void onAnimationRepeat(Animator animator) { }
})
.start();
}
} else {
Log.d(TAG, "showToolbar: no change");
}
}
The animation works perfectly except for the first time showToolbar(true) is called to show the toolbar. The view just shows up without animation the first time. I have scoured the site and found similar questions but the solutions doesn't seem to be working for me.
It might be worth noting that this happens only when we want the appBar to be hidden first. My guess is that maybe for the animation to
Update 1:
public static boolean isViewVisible(View view) {
if (View.VISIBLE == view.getVisibility()) return true;
else return false;
}
Update 2
I have removed isViewWithinScreenBounds() method because that check isn't really needed.
Be sure to set the initial values for visibility and translationY.
If you want your toolbar to be initially hidden and show up with the first animation, be sure to set android:visibility="invisible" and NOT "gone", and negative android:translationY like -56dp.
Try with this
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:translationY="-120dp"
android:layout_height="120dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SOME TEXT HERE" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Activity code
#BindView(R.id.app_bar)
AppBarLayout appBar;
#BindView(R.id.toolbar)
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
animateToolbar(false); //Just for testing purpose - delay execute of function animateToolbar() for 4 seconds
}
}, 4000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
animateToolbar(true);
return super.onCreateOptionsMenu(menu);
}
private void animateToolbar(boolean show) {
if (show) {
// As you can see in the xml layout initial position of the appBar is translated by its height to the top of the screen "-" sign
// Slide int from out of the screen to initial position -> from -120 dp (height of the app bar, see xml) to 0 dp
appBar.animate()
.translationY(0)
.setDuration(1000)
.start();
} else {
// Slide out from initial position to the top of the screen -> from 0 dp to -120 dp (height of the app bar, see xml)
appBar.animate()
.translationY(-appBar.getHeight())
.setDuration(1000)
.start();
}
}

fab.setVisibility(View.GONE) isn't working

I'm not using anchor, it should work.
Inicially, the visibility is gone (set by XML). When I press a button, it becomes visible (until here, works). Then, when I press another button, it should becomes gone, but nothing happens.
Reduced XML:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/tbTela3"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ToolBar"
app:titleTextColor="#757575"
app:subtitleTextColor="#757575" />
<android.support.design.widget.CoordinatorLayout
android:id="#+id/cLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tbTela3">
<ScrollView>
[...]
</ScrollView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:elevation="8dp"
android:src="#drawable/replay"
android:visibility="gone"/>
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
Reduced Main Activity:
public void ZoomIn() {
[...]
zoomIn.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation anim) {}
public void onAnimationRepeat(Animation anim) {}
public void onAnimationEnd(Animation anim) {
fab.setVisibility(View.VISIBLE); // WORKS FINE
}
});
fab.startAnimation(zoomIn);
}
[...]
public void Clear() {
[...]
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
readX.requestFocus();
cardII.setVisibility(View.GONE); // WORKS FINE TOO
fab.setVisibility(View.GONE); // BUT THIS DON'T
fadeOut.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation anim) {}
public void onAnimationRepeat(Animation anim) {}
public void onAnimationEnd(Animation anim) {
clear.setVisibility(View.INVISIBLE);
}
});
clear.startAnimation(fadeOut);
}
});
anim.start();
}
fab.setVisibility(View.GONE) doesn't work independent of where it is on Clear... I reduced the code to be more readable, hope this isn't a problem.
CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
p.setAnchorId(View.NO_ID);
fab.setLayoutParams(p);
fab.setVisibility(View.GONE);
Or Try
fab.show(); //show
fab.hide(); //hide
CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
p.setAnchorId(View.NO_ID);
fab.setLayoutParams(p);
fab.setVisibility(View.invisible);
Dont use GONE
INVISIBLE:
This view is invisible, but it still takes up space for layout purposes.
GONE:
This view is invisible, and it doesn't take any space for layout purposes.
INVISIBLE:
Adapter's getView() function called
GONE:
Adapter's getView() function didn't call, thus preventing views to load, when it is unnecessary
Now everything works. Final code:
public void ZoomIn() {
[...]
fab.show();
}
I removed everything and put fab.show()
public void Clear() {
[...]
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
readX.requestFocus();
cardII.setVisibility(View.GONE);
fab.setVisibility(View.GONE);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation anim) {}
public void onAnimationRepeat(Animation anim) {}
public void onAnimationEnd(Animation anim) {
clear.setVisibility(View.INVISIBLE);
}
});
clear.startAnimation(fadeOut);
}
});
anim.start();
}

Update Android UI doesnt work

im now searching for 2 hours for a small error that makes this code doesnt work:
The Activity:
UpdateThread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_fullscreen);
}
#Override
protected void onResume() {
t = new UpdateThread(this, this);
t.start();
super.onResume();
}
And the Thread:
public UpdateThread(FullscreenActivity a, Context c) {
this.c = c;
this.a = a;
}
#Override
public void run() {
if(enabled) return;
enabled = true;
while(true) {
a.runOnUiThread(new Runnable() {
#Override
public void run() {
RelativeLayout view = (RelativeLayout) a.findViewById(R.id.view);
view.removeAllViews();
try {
TextView t = new TextView(c);
t.setText("asd");
t.setVisibility(View.VISIBLE);
t.setX(22);
t.setY(123);
t.setScaleX(0.9f);
t.setScaleY(0.9f);
t.setBackgroundColor(Color.YELLOW);
view.addView(t);
} catch(Exception e) {e.printStackTrace();}
Log.d("Finished drawing!"," drawed!");
}
});
}
Layout XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/asd"/>
</RelativeLayout>
This code should add a TextView to the FullscreenActivity, but nothing happens.
Im using Android level 12, all Software up to date, my phone is the SGS3.
Thank you for you help, im looking forward to the solution :)

How to send data from fragment to fragment?

I have 1 layout. It contains 2 fragments. There are 2 buttons in this layout. When I clicked button 1, the fragment 1 is going to display. I am going to click button in fragment 1 content of textview display "welcome" then i click button 2 in main layout, fragment 2 is going to display and textview of fragment 2 is going to display content of textview of fragment 1.
Here This is my code.Please show and give me some comment for me.How to reslove this issue
The first is mainlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment1" />
<Button
android:id="#+id/btnFragment2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment2" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/container">
</LinearLayout>
The first is fragment1.xml
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
The first is fragment1.java
public class Fragment1 extends Fragment{
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = null;
view = inflater.inflate(R.layout.fragment1, null);
//I will get text after I press button and using bundle for storage
and send send to fragment
return view;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
}}
The first is fragment2.xml
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
The first is fragment2.java
public class Fragment2 extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2, null);
//In this I am going to using Bundle to get message from fragment1
}}
The first is MainActivity.java
public class MainActivity extends FragmentActivity {
Button btnFragment1, btnFragment2;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragmentManager = getSupportFragmentManager();
btnFragment1 = (Button) findViewById(R.id.btnFragment1);
btnFragment1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, new Fragment1(), "TAG_FRAGMENT1");
transaction.addToBackStack(null);
transaction.commit();
}
});
btnFragment2 = (Button) findViewById(R.id.btnFragment2);
btnFragment2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, new Fragment2(), "TAG_FRAGMENT2");
transaction.addToBackStack(null);
transaction.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}
Use a interface as a call back to the activity and then communicate the data to fragment2
http://developer.android.com/training/basics/fragments/communicating.html
There is a Example in the above link
#Raghunandan has a good answer. Not the only option though, you could use a BroadcastManager or LocalBroadcastManager. This way you can easily respond to events across Activities, Fragments, Services, etc.
how to use LocalBroadcastManager?
You can use Activity as a proxy between fragments this is how you can inform Activity about event in fragment:
public class FragmentA extends Fragment {
OnSomethingDoneInFragmentListener mListener;
//this inteface must implement Activity that use the fragment
public interface OnSomethingDoneInFragmentListener {
public void onSomethingDone(Object someObject);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnSomethingDoneInFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnSomethingDoneInFragmentListener");
}
}
}
Try to use EventBus, it saves you a lot of work.
EventBus is an Android optimized publish/subscribe event bus. A
typical use case for Android apps is gluing Activities, Fragments, and
background threads together. Conventional wiring of those elements
often introduces complex and error-prone dependencies and life cycle
issues. With EventBus propagating listeners through all participants
(e.g. background service -> activity -> multiple fragments or helper
classes) becomes deprecated. EventBus decouples event senders and
receivers and thus simplifies communication between app components.
Less code, better quality. And you don't need to implement a single
interface!
Define your event, which is a data object:
class MyClickEvent {
// ...
public MyClickEvent(String field1, int field2) {
// ...
}
}
In a Fragment, register itself to handle event:
class MyFragment extends Fragment {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
EventBus.getDefault().register(this, MyClickEvent.class);
}
public void onEvent(MyClickEvent event) {
// handle the event
}
}
Post event on button click:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getDefault().post(new MyClickEvent("Some data", 123456));
}
});

Android progressbar with runnable interface

I have a code like the below:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
BasicViews2Activity.java
public class BasicViews2Activity extends Activity
{
static int progress;
ProgressBar progressBar;
int progressStatus = 0;
Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = 0;
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//---do some work in background thread--
new Thread(new Runnable()
{
public void run()
{
//---do some work here--
while (progressStatus < 10)
{
progressStatus = doSomeWork();
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
progressBar.setVisibility(View.GONE);
}
});
}
//---do some long running work here--
private int doSomeWork()
{
try {
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
}
}
Why did we use two runnable objects inside the thread class to cancel the progressbar? Couldn't we do it inside the first runnable obj – just after while loop, without another object?
The asyncTask class can be used easily with progressbars. AS they have an onPreexecute and onPostexecute with which we can update the ui thread from the background activity.
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Hope this makes your code easier...
#shaon007 sorry for late post, Yes you can do it with single runnable class
Like below
create your xml just the way you have created
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressbar"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Keep visibility option invisible for the start
Then in your mainActivity you have to do three things those are
1) Create Handler object
2) Create anonymous runnable class
3) Call run() method from runnable with setting your progressbar visibility
As follows
public class MainActivity extends AppCompatActivity {
Handler handler;
private ProgressBar progressBar;
private int checkCount = 5000; // counter for progressbar visibility
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
handler = new Handler(); // handler object
// runnable class
final Runnable runnable = new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
checkCount -= 1000;
if(checkCount > 0) {
handler.postDelayed(this,1000);
}
else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this,"Progress bar invisible",Toast.LENGTH_SHORT).show();
// Or your other work
}
}
};
handler.postDelayed(runnable,1000); // will start run() method after 1 second
}
}
And your done

Categories

Resources