Java – passing listeners to custom snippets in Android
•
Java
I'm creating a view pager in my application and using a class that extends fragment When I create an instance, I can pass all elements (images, text, etc.) and store them with the bundle to use it in oncreate But I can't store the listener of the button in the clip This is my class:
public class RegWizardFragmentInfo extends Fragment { private static final String IMAGE = "image"; private static final String TEXT = "text"; private static final String BUTTON = "buttonText"; private View.OnClickListener buttonCallBack; private Button button; private int image; private int text; private int buttonText; public RegWizardFragmentInfo newInstance(int image,int text,int buttonText,View.OnClickListener callback) { RegWizardFragmentInfo fragment = new RegWizardFragmentInfo(); Bundle bundle = new Bundle(); bundle.putInt(IMAGE,image); bundle.putInt(BUTTON,buttonText); bundle.putInt(TEXT,text); fragment.setArguments(bundle); fragment.setRetainInstance(true); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.onActivityCreated(savedInstanceState); this.image = getArguments().getInt(IMAGE); this.text = (getArguments() != null) ? getArguments().getInt(TEXT) : -1; this.buttonText = (getArguments() != null) ? getArguments().getInt(BUTTON) : -1; } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment,container,false); //Extract all the views and add the image and texts return rootView; }
So, how do I store the listener I got in newinstance on the button of oncreateview method?
Thank you for your help
Solution
You can use callbacks in clips:
public class RegWizardFragmentInfo extends Fragment { private Button button; private OnClickCallback callback; public interface OnClickCallback { void onClick(); } @Override public void onAttach(Context context) { super.onAttach(context); callback = (OnClickCallback) context; } @Nullable @Override public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) { return super.onCreateView(inflater,savedInstanceState); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { callback.onClick(); } }); } }
And implement this new interface in your parent activity
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码