Hi I am trying to find out how to replace a fragment by clicking on a button within a fragment.
I tried looking into this article but it did not work for me.
View view = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getView();
btnGoToSignUp = view.findViewById(R.id.btnGoToSignUp);
I tried this but it comes up with the error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.Fragment.getView()' on a null object reference
You could just do this:
Interface:
public interface BtnClickable {
void myClickMethod(View v);
}
Fragment:
public class SomeFragment {
BtnClickable btnClickable;
//...onCreateView, etc.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_add_note, container, false);
Button btnGoToSignUp = root.findViewById(R.id.btnGoToSignUp);
btnGoToSignUp.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
btnClickable.myClickMethod(v);
}
});
}
public static void setClickListener(BtnClickable listener){
btnClickable=listener;
}
Activity:
class MyActivity implements BtnClickable {
//...onCreate etc instantiating your fragments
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filters);
SomeFragment.setClickListener(this);
}
public void myClickMethod(View v) {
// you can listen here for btn clicked
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.