在Android中,要获取一个Activity实例,您可以使用以下方法:
getActivity()
方法。首先确保您的类实现了ActivityLifecycleCallbacks
接口,然后在onActivityCreated()
方法中获取Activity实例。例如:import android.app.Activity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import java.util.ArrayList;
import java.util.List;
public class MyLifecycleObserver implements LifecycleObserver {
private Activity mActivity;
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onActivityCreated(Activity activity) {
mActivity = activity;
}
public Activity getActivity() {
return mActivity;
}
}
然后,在您的Activity中注册这个LifecycleObserver:
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LifecycleRegistryOwner;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyLifecycleObserver myLifecycleObserver = new MyLifecycleObserver();
getLifecycle().addObserver(myLifecycleObserver);
}
}
现在您可以通过调用myLifecycleObserver.getActivity()
来获取MainActivity的实例。
ContextWrapper
。首先,创建一个ContextWrapper
实例并传递您的Activity作为参数:import android.content.Context;
import android.view.ContextThemeWrapper;
public class MyContextWrapper extends ContextThemeWrapper {
public MyContextWrapper(@NonNull Context base, int themeResId) {
super(base, themeResId);
}
public Activity getActivity() {
return (Activity) base;
}
}
然后,在您的Activity中创建一个MyContextWrapper
实例并传递它:
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyContextWrapper myContextWrapper = new MyContextWrapper(this, R.style.AppTheme);
}
}
现在您可以通过调用myContextWrapper.getActivity()
来获取MainActivity的实例。