首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >findViewById of TextSwitcher替换片段后返回null

findViewById of TextSwitcher替换片段后返回null
EN

Stack Overflow用户
提问于 2014-05-02 01:34:30
回答 1查看 395关注 0票数 1

我在网上找到的几乎所有东西都试过了。

我清理了这个项目,试着打电话到视图的上下文中,很多其他的事情都没有用。

这是我的活动代码

代码语言:javascript
复制
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类

代码语言:javascript
复制
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

代码语言:javascript
复制
<TextSwitcher 
        android:layout_marginTop="50dp"
        android:id="@+id/tswitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-02 01:42:25

当您调用ft.commit()时,您的片段不一定是可用的。

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

示例:

代码语言:javascript
复制
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;
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23419446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档