就像我的标题所说,我正在
Android项目的ActionBarActivity类中寻找相当于getActivity()的东西.
我想在AsyncTask声明对象中传递一个Activity参数,因为我在我的自定义AsyncTask扩展类中使用了一个Activity对象
这是我项目的一个示例最简单的代码
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,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(); } } }; }
有一段时间,我认为从ActionBarActivity类使用getParent(),但它返回一个null对象.
那么如何在ActionBarActivity类中获取我想要的Activity对象?
解决方法
试试nameofactivity.this而不是getActivity()
我总是在Fragments Activities中使用getActivity(),在任何其他类型的Activity中使用.this.