简体   繁体   中英

Can you pass an instance of a class from inside a class in Android?

I'm implementing a fragment, and on the edit of a text (using TextWatcher), I'm passing data to the parent activity using an interface.

I'm wondering though if it's possible to pass the instance of the class itself as the data being passed to the activity? So that I don't have to transfer every single String field one parameter at a time.

So could I do;

Activity:

Fragment frag = new FragmentClass();
// ... start the fragment

The in FragmentClass.java:

editText = findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
    ...
    public void afterTextChanged(...) {
    listener.onChangedListener(PASS IN THE INSTANCE OF THE CLASS ITSELF???);
    }
});

This is to avoid needing to do:

listener.onChangedListener(String field1, String field2, String field3, etc..);

If i understand you corrent so you should do somethink like this

    listener.onChangedListener(FragmentClass.this);

And on other side your listener should receive the instance of this class

    interface MyListener {
        void onChangedListener(FragmentClass fragmentClass);
    }

You can access a public property on your parent activity from your fragment. Not sure if this is what you want to accomplish. You can try this.

In Activity

public String myText;

In Fragment

YourActivity parentActivity;
parentActivity = (YourActivity)getActivity(); 

//access the string property of your activity or do something else. Ex. parentActivity.myText = "Sample text" 

This is just draft of a code on what I can remember as I am not on an IDE right now.

You can create DTO(data transfer object, just simple class) class.

class MyClass {
   String field1;
   String field2;
   String field3;
   MyClass(
       String field1,
       String field2,
       String field3
   ) {
     this.field1 = field1;
     this.field2 = field2;
     this.field3 = field3;
   }
}

And use it like:

MyClass dto = MyClass(field1, field2, field3);
listener.onChangedListener(dto);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM