简体   繁体   中英

How to get the View for a class, that extends a class that extends Fragment/activity etc

I am having a problem were I have:

class x that extends y

and class y that extends Fragment

I wan to be able to do things in x that for eg get a textview with ID and change the text. To do this, I must get the view but I get problems. I have tried Super.getView, and I have tried to save the view in y and access from x but it does not work.

Why is this?

edit: example code:

public x extends fragment{

}

public y extends x{
    public y(){
         eg TextView t = this.getView().getById(...)
         which will fail as cant get the view
    }
}

I would save the TextView as a protected var in the class that extends fragment so that you have access to it from its subclasses:

public class x extends Fragment {
    protected TextView myTextView;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        myTextView = view.findViewById(...);
    }
}

public class y extends x {
    public void y() {
        if (myTextView != null) {
            myTextView...
        }
    }
}

Keep in mind that it will only have the myTextView assigned after onViewCreated is called on that fragment, but you can check if it has been defined (it's not null) before doing whatever you have to.

PS: In the case of extending an Activity it could be assigned in onCreate method by calling the findViewById method of that activity:

public class x extends Activity {
    protected TextView myTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ....

        myTextView = findViewById(...);
    }
}

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