-9

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

Vivek Pagar
  • 29
  • 1
  • 8
  • 1
    why not set listener in `Fragment`? – Abdul Kawee Feb 19 '18 at 07:02
  • 5
    Possible duplicate of [Communicating between a fragment and an activity - best practices](https://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices) – ADM Feb 19 '18 at 07:03
  • You can not use `findViewById()` which does not exists in same component . You can communicate between Fragment and Activity. – ADM Feb 19 '18 at 07:04
  • `EditText edittext =fragmentview.findViewById(R.id.edittext);` and set listener in Fragment – Jyoti JK Feb 19 '18 at 07:05

4 Answers4

0

To find view by id from fragment, add this:

EditText edittext = getActivity().findViewById(R.id.edittext);
Ezra Lazuardy
  • 406
  • 6
  • 17
0

The simple solution is

EditText editText = (EditText)getActivity().findViewById(R.id.viewid);
if( editText != null){
  // set listener here 
}
Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50
0

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.

0

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
    }  
    });
Ashish Kumar
  • 374
  • 4
  • 11