我試圖將數據從活動A到FragmentActivity B的意圖傳遞給片段B.活動A的按鈕啓動FragmentActivity B.「年份」字符串設置一個過濾器與我查詢遠程服務器上的mysql數據庫。下面的代碼工作,但只有一半的時間。片段內的意圖只有一半的時間工作
我不知道是什麼導致它過濾一些時間,有時它只是返回未經過濾的整個表。我猜它必須與我在片段中使用的意圖有關,因爲過濾器在沒有片段的應用程序版本中沒有問題地工作。我將意圖從活動A發送到FragmentActivity B到碎片B的方式似乎效率不高。我該如何解決這個問題?
活動答:
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(FindMovie.this, ShowMovies.class);
intent.putExtra("year", year1);
startActivity(intent);
}
});
FragmentActivity B:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_movies);
if (getSupportFragmentManager().findFragmentByTag(TAG) == null) {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, new ImageGridFragment(), TAG);
ft.commit();
}
Intent i = getIntent();
year = i.getStringExtra("year");
//resend through another intent to the fragment B
Intent intent = new Intent(getApplicationContext(), ImageGridFragment.class);
intent.putExtra("year", year);
}
片段B:
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);
Bundle extras = getActivity().getIntent().getExtras();
year = extras.getString("year");
return v;
}
多麼美妙的答案!非常感謝。它解決了這個問題。 「線程計時問題」是問題所在,我實際上只需將異步任務移動到Bundle extras = getActivity()。getIntent()。getExtras(); \t \t \t \t year = extras.getString(「year」); – Jerome
不客氣:D – LuckyMe
LuckyMe,這真的有效。我有一個小問題,我的片段處於可選標籤視圖,所需片段位於第5個選項卡中。當我使用這個代碼時,它直接嵌入第5個屏幕。我如何改變它 –