我正在尝试实施Google sign in button:
在我的主要活动中,我有:
private GoogleApiClient mGoogleApiClient;
//used to identify result
private static final int RC_SIGN_IN = 1253;
private static final String TAG = "SignInActivity";
private TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create fragment
LoginFragment newFragment = new LoginFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
//transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, (GoogleApiClient.OnConnectionFailedListener) this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//WONT WORK
setDefaults()
}
要设置onclicklistener,我想运行以下方法来设置监听器:
public void setDefaults()
{
responseText = (TextView)findViewById(R.id.googleResponse);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
我无法从主要活动的oncreate中调用它,因为findViewById(R.id.googleResponse);将是null。
我不想在loginfragment中使用我的逻辑,但想在mainActivity中使用它。
如何将onclicklisterner设置为sign_in_button(位于loginfragment中),同时避免使用null ptr。
答案 0 :(得分:1)
来自onResumeFragments
的文档:
这是onResume()的片段定向版本,您可以覆盖该版本以在其片段恢复的同一点执行Activity中的操作。一定要经常打电话给超级班。
因此,在此回调中,您确定您的片段处于onResume()
d状态并且布局了视图层次结构。
但这不是最好的解决方案。 Imho,在片段中设置观察者是简洁的方式。只需创建一个界面。让您的活动实现该接口,并在片段的onViewCreated()
回调中调用该接口的实现。
if (getActivity() instanceof YourInterface) {
((YourInterface) getActivity()).performInitialization();
}