2014-03-01 78 views
0
@Override 
public Fragment getItem(int position) { 
    CharacterFragment fragment = new CharacterFragment(); 
    View rootView = fragment.getView(); 
    TextView character = (TextView) rootView.findViewById(R.id.character); 
    character.setText(name[position]); 
    return fragment; 
} 

这是我的代码,用于更改ViewPager中的片段。该片段只有一个文本视图。基本上,我只是用我的名字拼写字母。所以,根据索引,我必须设置片段的TextView中的文本。更改ViewPager中片段的文本

通过上面的代码,程序吹了一个NullPointerException,因为布局还没有膨胀,所以我认为。

什么是正确的方式来改变Fragment的内容? 是否有回调方法让我知道它已经变得可见?

回答

2

没有回调。您可以在创建片段时将文本作为参数发送到片段,并在片段内设置文本。

喜欢的东西:

@Override 
public Fragment getItem(int position) { 
    CharacterFragment fragment = CharacterFragment.newInstance(name[position]); 
    View rootView = fragment.getView(); 
    return fragment; 
} 

CharacterFragment.newInstance(String name)方法看起来像:

public static CharacterFragment.newInstance(String name) { 
    CharacterFragment fragment = new CharacterFragment(); 
    Bundle args = new Bundle(); 
    args.put("NAME_ARG", name); 
    fragment.setArguments(args); 
    return fragment; 
} 

然后在onCreateView()您通过方法得到的参数,你会得到与关键NAME_ARG字符串。你有它!说得通?

+0

问题是对'TextView'的引用总是返回为null。我尝试在片段的onResume()中使用'getView()。findViewById(R.id.myTextView)',但返回的值始终为空。 –

+0

编辑答案以提供更多详细信息。我们的想法是在创建片段时将字符串作为参数发送,然后在'onCreateView'中从参数中获取String并将其设置为TextView。 – gunar

+0

作品!一个简单的问题是:如何让文本足够大,以便每个角色都能填满屏幕,而不管屏幕的大小如何? :) –

1

这不是使用getView()的正确方法。完成你想要的东西的方式有点不同。为此,您应该将字符串(在此例中为name[position])传递给该方法。 但是你应该记住,碎片不应该与他们的构造函数实例化,而不是创建一个静态方法,我会告诉你:

@Override 
public Fragment getItem(int position) { 
    CharacterFragment fragment = CharacterFragment.newInstance(name[position]); 
    return fragment; 
} 

,然后里面CharacterFragment.java

public static CharacterFragment newInstance(String name) { 
    Bundle bundle = new Bundle(); 
    bundle.putString("key_name",name); 

    CharacterFragment fragment = new CharacterFragment(); 
    CharacterFragment.setsetArguments(bundle); 

    return fragment; 
} 

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

    View view = inflater.inflate(R.layout.fragment_xml_file, container, false); 

    // AND HERE WE GO 
    String name = getArguments().getString("key_name"); 
    TextView character= view.findViewById(R.id.character); 
    character.setText(name); 

    return view; 
} 
+0

*片段不应该用它们的构造函数实例化*马里兰大学提供的在线课程显示了我使用'new'的方式:O –