William Calvin
William Calvin

Reputation: 625

fragment.getView() return null after backpressed

I try to change textview under attached fragment on activity so i stored attachedFragment as variable as code below

    @Override
    public void onAttachFragment(android.support.v4.app.Fragment fragment) {
        super.onAttachFragment(fragment); 
        attachedFragment = fragment;
    }

then when a button is clicked I call following code

        if(attachedFragment !=  null && attachedFragment.getView() != null)
        {
            TextView tvGender = (TextView) attachedFragment.getView().findViewById(R.id.tv_gender);
            if(tvGender!=null)
                tvGender.setText(R.string.title_step_one_gender);
        }

When I start the activity and it works fine until i changed into the next fragment and pressed back; the attachedFragment.getView() always returns null

My question:

  1. How is it possible it returns null while the first time is okay?
  2. What is the best solution to change textview/any other control within fragment? There are lots of fragments and I only need to change attached fragment.

nb: All code above are under main activity

Upvotes: 0

Views: 462

Answers (1)

GLee
GLee

Reputation: 5093

Please correct me if I misunderstood your question. It sounds like your situation is, you attach fragment A, then you attach fragment B, then you press back, leaving you with fragment A. In this case, attachedFragment is just a variable, so it continues to point to B, but since B is now detached, it is null. Pressing back will not repopulate the variable attachedFragment with fragment A.

Try using findFragmentById or findFragmentByTag. Check out this thread for more info.

Upvotes: 1

Related Questions