2012-02-22 42 views
2

我有一個FragmentPagerAdapter,它包含大量Fragment對象,通過它我可以通過水平滑動進行滑動。從Fragment對象訪問FragmentActivity中的元素

我想知道如果我可以在Fragment對象內訪問FragmentActivity中的元素(「elementToBeChanged」)嗎?我想從Fragment類傳遞一個String到FragmentActivity對象中的TextView元素。

public class GalleryPagerActivity extends FragmentActivity implements OnClickListener { 

private TextView elementToBeChanged; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    super.setContentView(R.layout.gallery_pager); 

    elementToBeChanged = (TextView) findViewById(R.id.tvTop); 
    elementToBeChanged.setOnClickListener(this); 

} 
} 

我該怎麼做?每次看到Fragment對象時(通過滑動),TextView元素都必須更新。

它應該是這個樣子:

public class GalleryFragment extends Fragment { 

private FragmentActivity fa; 
private LinearLayout ll; 

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

    fa = super.getActivity(); 

    ll = (LinearLayout) inflater.inflate(R.layout.gallery_fragment, container, false); 
... 
// //////// 
// UPDATE THE "TextView elementToBeChanged" object in the parent FragmentActivity class HERE WHENEVER THIS FRAGMENTS BECOMES ACTIVE/VISIBLE... 
// //////// 

    return ll; 
} 

回答

10

在你GalleryPagerActivity創建一個函數,如updateTextView(字符串文本)。該函數將設置TextView爲任何輸入值。然後在你的GalleryFragment中簡單地調用這個函數以顯示文本:

((GalleryPagerActivity)getActivity()).updateTextView("my text"); 
+0

謝謝!這很好用! – 2012-02-23 01:58:02

+0

我能爲相反的情況做些什麼?我想從fragmentActivity更新片段中的元素。我跟着這個鏈接:http://stackoverflow.com/questions/18486952/get-id-of-textview-in-fragment-from-fragmentactivity-in-viewpager ;;;;;;但他們表示:「每次設置文本時都不要創建新對象,請使用您用於查看傳呼機的相同片段對象。」我如何訪問該fragmentObject?所以我跟着這個鏈接:http://stackoverflow.com/questions/14035090/how-to-get-existing-fragments-when-using-fragmentpageradapter ;;;;;但我現在不知道該怎麼辦! – 2014-07-18 19:23:50

+0

請參閱我的相關問題:http://stackoverflow.com/questions/24833912/refresh-fragment-ui-from-fragmentactivity – 2014-07-19 07:45:12