Reputation: 463
I am new to Android development and I want to link a button with the animation. I am getting error near runOnUiThread()
and getApplication()
. When I add this in as an activity it is fine, but when declared in MainFragment
it gives error. However when I fix the errors, it creates a method and returns false.
public class MainFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
ImageButton btnFacebook = (ImageButton)rootView.findViewById(R.id.facebook2);
final Animation alpha = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_alpha);
btnFacebook.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
arg0.startAnimation(alpha);
Thread thread = new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep(1000);
}catch(InterruptedException e){
}
runOnUiThread(new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplication(),FacebookActivity.class));
}
});
}
};
thread.start();
}});
return rootView;
}}
In the XML file I only have the facebook imagebutton. When I click that, it has to trigger the animation and then onclick event has to happen, but I don't know why this error is popping up:
The method runOnUiThread(new Runnable(){}) is undefined for the type new Thread(){}
And near getapplication() method The method getApplication() is undefined for the type new Runnable(){}
If I create the two methods the error goes away, but then when I click onto the button it will not go to the facebookActivity.java file.
Can anyone tell/help what should I add to solve this issue. Thanks.
Upvotes: 7
Views: 9439
Reputation: 6166
Please use getActivity()
instead of using getApplication()
.
which returns the activity associated with a fragment. The activity is a context.
Upvotes: 2
Reputation: 14590
runOnUiThread(new Runnable(){}) is method in Activity not in the Fragment.
so you need to change
runOnUiThread(new Runnable(){})
into
getActivity().runOnUiThread(new Runnable(){})
For your requrement it is better to use Handler
instead of Thread
for waiting 1000 milli seconds..
Upvotes: 2
Reputation: 100418
runOnUIThread(...)
is a method of Activity
.
Therefore, use this:
getActivity().runOnUIThread(...);
But, beware. You're dealing with asynchronous threads, so your Fragment
might be detached from its Activity
, resulting in getActivity()
returning null
. You might want to add a check if(isAdded())
or if(getActivity() != null)
before executing.
Alternatively, use an AsyncTask
, which handles this running on the ui thread by itself.
Upvotes: 10