在我的FragmentActivity中,我有一個片段。該片段從服務器加載數據。 我想我們用戶點擊刷新按鈕,然後我調用片段中的方法並執行刷新過程。Android,如何重新啓動/刷新從FragmentActivty片段?
我在FragmentActivity中創建了一個接口,並在用戶單擊刷新按鈕時設置其變量。該代碼是這樣的:
public class MainScreen extends FragmentActivity {
public interface OnRefreshSelected {
public void refreshFragment(boolean flag);
}
private OnRefreshSelected onRefreshSelected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Try to create MainScreen...");
setContentView(R.layout.activity_main);
onRefreshSelected = (OnRefreshSelected) MainScreen.this;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
onRefreshSelected.refreshFragment(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
而在片段I類實現該接口:
public class CategoryFragment extends Fragment implements OnRefreshSelected {
@Override
public void refreshFragment(boolean flag) {
Log.i(TAG, "refresh requested. Try to reload data for this fragment...");
getData();
}
}
當運行時,應用程序崩潰和logcat的示出這樣的信息:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.astro.recipe.activities/com.astro.recipe.activities.MainScreen}: java.lang.ClassCastException: com.astro.recipe.activities.MainScreen
和指向此行:
onRefreshSelected = (OnRefreshSelected) MainScreen.this;
從主機訪問片段方法的最佳方式是什麼? 任何建議,將不勝感激。由於
我能用AppCompatActivity代碼您的活動。 – 2015-12-11 07:27:15