I have one activity which is hosting several tabs(Fragment), now I want to get EditText by id from tab(Fragment) to its hosting activity and set listener on it.
So please help me to get rid of it.
Thanks in advance
I have one activity which is hosting several tabs(Fragment), now I want to get EditText by id from tab(Fragment) to its hosting activity and set listener on it.
So please help me to get rid of it.
Thanks in advance
To find view by id from fragment, add this:
EditText edittext = getActivity().findViewById(R.id.edittext);
The simple solution is
EditText editText = (EditText)getActivity().findViewById(R.id.viewid);
if( editText != null){
// set listener here
}
In your Activity
public EditText editText;
if(editText != null)
editText.setOnClickListner(this);
In your Fragment
Activity activity = (Activity)context;
//where context is your fragment's context
activity.edtText = (EditText)findViewById(R.id.viewid);
Make sure you set listener when editText is not null otherwise you will get null pointer exeption.
There can be multiple solutions to this. In my opinion the best way is to make an interface named Callback as below
public interface Callback
{
public void onListenerActionPerformed(Some args);
}
Now in whatever fragment you want the listener to be attached, write a function
private Callback callback;
public void setCallback(Callback callback)
{
this.callback=callback;
}
Now register the listener on your EditText in the fragment and inside the body of the corresponding function write
callback.onListenerActionPerformed(Some parameter)
Now from your activity, right below where you have instantiated the fragment write,
fragmentInstanceName.setCallback(new Callback(){
public void onListenerActionPerformed(Some args){
//Your implementation
}
});