替换片段后,TextSwitcher的findViewById返回null

时间:2014-05-02 01:34:31

标签: android android-fragments nullpointerexception

我几乎尝试过在互联网上找到的所有内容。

我清理了项目,尝试在视图的上下文中调用,许多其他的东西,但无济于事。

这是我的活动代码

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" />

1 个答案:

答案 0 :(得分:1)

只要您拨打ft.commit(),就不能保证您的片段可用。

尝试从片段的onCreateView()方法访问textSwitcher,而不是直接从活动中访问。

示例:

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;
    }