问题
Like my title says, i'm looking for an equivalent of getActivity()
in my ActionBarActivity
class in my Android project
.
I want to pass an Activity
parameter in AsyncTask
declaration object, because i'm using an Activity
object in my custom AsyncTask
extended class
Here an example simplest code of my project
public class EventCreator extends ActionBarActivity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_even_creator);
View v = getLayoutInflater().inflate(R.layout.activity_even_creator,null);
this.context = this.getBaseContext();
final Button createButton = (Button)findViewById(R.id.createEventButton);
createButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTask<Void,Void,Boolean> eventCreatorSend = new SendEvents(/* here need activity object */);
eventCreatorSend.execute();
}
});
}
class SendEvents extends AsyncTask<Void,Void,Boolean> {
public Activity act;
SendEvents(Activity a) {
this.act = a;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(Void... params) {
SystemClock.sleep(5000);
return true;
}
@Override
protected void onPostExecute(Boolean params) {
if (params){
((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.GONE);
act.finish();
}
else {
((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.VISIBLE);
Toast.makeText(act,"Fail to send event",Toast.LENGTH_SHORT).show();
}
}
};
}
In a time, i thought use getParent()
from ActionBarActivity
class, but it return a null object.
So how to get the Activity object i want in ActionBarActivity
class ?
回答1:
Try nameofactivity.this instead getActivity()
I always use getActivity()
in Fragments
Activities and .this in any other kind of Activity
.
回答2:
Oh damn ! I just found a solution just after posting my ask.
I use MyClass.this, and it's done. Like this :
AsyncTask<Void,Void,Boolean> eventCreatorSend = new SendEvents(EventCreator.this);
eventCreatorSend.execute();
Hope that's can help someone !
回答3:
The easiest way is an Activity variable
// in your fragment
Activity myActivity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//fragment shouts "i know my father!!!"
myActivity = activity; //
}
now your activity instance(The father) can be represented anywhere
来源:https://stackoverflow.com/questions/30496286/android-equivalent-of-getactivity-from-in-actionbaractivity