2015-08-19 113 views
1

我有一個FragmentPagerAdapter,顯示可變數量的片段。其中每個片段的onCreateView方法如下所示:銷燬和重建FragmentPagerAdapter

public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    if (container == null) 
     return null; 

    View v = inflater.inflate(R.layout.my_fragment, container, false); 
    TextView tv = (TextView)v.findViewById(R.id.my_text_view); 
    Log.d(TAG, "Setting TextView text to: " + someString); 
    tv.setText(someString); // Where someString is some global that will change later. 
} 

接下來,我將someString更改爲一些新值。 然後我重建FragmentPagerAdapter。我的目的是摧毀舊的和新的開始:

mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(...); 
mMyViewPager.setAdapter(mMyFragmentPagerAdapter); 

片段中的我的調試語句顯示字符串的新值不如預期,但TextView的仍然顯示字符串的舊值。

有人知道發生了什麼嗎?

回答

1

修好了!

我的TextView實際上是一個EditText,所以我開始尋找爲什麼一個EditText可能不刷新,StackOverflow上再次來到救援:

EditText Settext not working with Fragment

原來,EditText上有清爽的一個問題片段的onCreateView方法。所以我將我的代碼從onCreateView中移出並放入onStart中,並且工作正常!

我很想知道爲什麼EditText無法在onCreateView中刷新。這只是b。。

0

那可能是因爲你使用的是正規的FragmentManager。嘗試交給你的MyFragmentPagerAdapter實例ChildFragmentManager的構造函數。

mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager()); 

編輯: 如果使用FragmentActivity嘗試添加:

viewPager.removeAllViews(); 
viewPager.setAdapter(null); 

設置新Adapter之前。

+0

我從FragmentActivity構造MyFragmentPagerAdapter。我無法訪問兒童片段管理器。我通過它getSupportFragmentManager()。 – SilentByte

+0

看我編輯答案。無論如何,爲什麼你不只是更新TextView而不是所有的質量? – yshahak

+0

仍然無法正常工作。奇怪的是,我可以設置文本顏色和可見性,並且它會改變。但是設置文本本身不起作用。順便說一句,一旦我設置文本,當我在TextView上調用getText時,它會返回新值。但它顯示了舊的價值! – SilentByte