Domanda

I've tried almost everything I found on internet.

I cleaned the project, tried to call in view's context, many other things but to no avail.

Here's my code in activity

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    ft.replace(R.id.container, new displayFragment() );
    ft.addToBackStack(null);
    // Start the animated transition.
    ft.commit();

    TextSwitcher textSwitcher = (TextSwitcher) findViewById(R.id.tswitch);
    if(textSwitcher == null)
    {
        Toast.makeText(getApplicationContext(), "Pointer is null",
                Toast.LENGTH_LONG).show();
    }

displayFragment class

public class displayFragment extends Fragment{

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_display, container, false);
    }

fragment_display.xml

<TextSwitcher 
        android:layout_marginTop="50dp"
        android:id="@+id/tswitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
È stato utile?

Soluzione

Your fragment is not guaranteed to be available as soon as you call ft.commit().

Try accessing your textSwitcher from the onCreateView() method of your fragment, rather than directly from the activity.

Example:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_display, container, false);

        TextSwitcher textSwitcher = (TextSwitcher) rootView.findViewById(R.id.tswitch);
        //Do stuff with textSwitcher

        return rootView;
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top