Reputation: 101
am trying to make the text under my login button "no account yet? signup now" when clicked to send me to my RegisterFragment.so i added an OnClickListener for it like this in my LoginFragment.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView signup = (TextView) getView().findViewById(R.id.signup);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginFragment.this.startActivity(new Intent(getActivity(), RegisterFragment.class));
}
});
but when i run the code the app crashes on this line
TextView signup = (TextView) getView().findViewById(R.id.signup);
this is my fragment_login.xml file
<TextView android:id="@+id/signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="No Account Yet? Signup_now"
android:gravity="center"
android:textSize="16dp"
android:clickable="true"/>
please guys i really need your help.
Upvotes: 0
Views: 71
Reputation: 3480
onCreateView() method is responsible for creating view, so you should first create it.
You can't directly use getView()
inside onCreateView()
.
You need to inflate it first like
View view = inflater.inflate(R.layout.my_layout, container, false);
Then use
TextView signup = (TextView) view.findViewById(R.id.signup);
So full code should look like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_layout, container, false);
TextView signup = (TextView) view.findViewById(R.id.signup);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
return view;
}
On side note, setting up click listener initializing TextView's etc should be done inside onViewCreated()
. onCreateView()
should just create & return the view.
like
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
TextView signup = (TextView) view.findViewById(R.id.signup);
// and so on...
}
Upvotes: 2
Reputation: 191874
I would recommend not setting a click listener into something you want to type into
You can't call getView
before onCreateView
has actually returned a proper View
RegisterFragment.class
is not an Activity, you cannot startActivity
for it. Use the FragmentManager
getSupportFragmentManager().beginTransaction()
.replace(R.id.<someContainer>, RegisterFragment.class)
.commit();
Or you can see the documentation on Communication between Fragments to see how you might implement on onLogin()
or onRegistrationSelected()
action to swap out to the registration fragment or "post-login" main fragment.
Upvotes: 0