2014-03-01 73 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 –