我有这个应用程序,我使用片段,但不知何故每次我启动应用程序,每个活动(片段)启动两次。我对此表示不满,但我找不到答案。有人能帮助我吗?
这是我的主要FragmentActivity:
public class TestSearch extends Activity {
//this activity starts a fragment
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
// private ActionBarDrawerToggle mDrawerToggle;
private ArrayList<Device> devices;
private ArrayList<Recepie> recepies, mainRecepies;
private ArrayList<Recepie> searchResult;
private LinearLayout sideWrapper;
private EditText src;
ArrayList<Categories> cats;
boolean isTablet = false;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_search);
Log.v("--", "started");
if (Constants.isTablet(this)) {
isTablet = true;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
devices = new ArrayList<Device>();
recepies = new ArrayList<Recepie>();
mainRecepies = new ArrayList<Recepie>();
devices = (ArrayList<Device>) getIntent().getSerializableExtra(
Constants.DEVICES_EXTRA);
recepies = getIntent().getParcelableArrayListExtra("all");
mainRecepies = getIntent().getParcelableArrayListExtra(
Constants.MAINRECEPIES);
// mTitle = mDrawerTitle = getTitle();
cats = new ArrayList<Categories>();
cats = (ArrayList<Categories>) getIntent().getSerializableExtra("cats");
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sideWrapper = (LinearLayout) findViewById(R.id.listwraper);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
// View header = getLayoutInflater().inflate(R.layout.search_item,
// null);
src = (EditText) findViewById(R.id.search_est);
src.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
Log.v("--", "Start search");
if (src.getText().length() > 0) {
searchResult = new ArrayList<Recepie>();
final ProgressDialog progress = ProgressDialog.show(
TestSearch.this,
getString(R.string.please_wait),
getString(R.string.getting_search_results),
true);
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
src.getWindowToken(), 0);
};
@Override
protected Void doInBackground(Void... params) {
searchResult = getSearchResults(src.getText()
.toString());
return null;
}
protected void onPostExecute(Void result) {
// set screen to search fragment
Fragment fragment = new SideSearchFragment();
Bundle args = new Bundle();
args.putString("cat-title", src.getText()
.toString());
args.putSerializable("cats", cats);
args.putBoolean(Constants.SEARCH, true);
args.putParcelableArrayList(
Constants.SEARCH_RESULTS, searchResult);
fragment.setArguments(args);
progress.dismiss();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack("search_results")
.commit();
// setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(sideWrapper);
// clear search text and hide keyboard
src.setText("");
};
}.execute();
}
return true;
}
return false;
}
});
// mDrawerList.addHeaderView(header);
SideAdapter adapter = new SideAdapter(this, cats);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
initActionBar();
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
showMainFragment();
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void showFavoritesFragment() {
Fragment fragment = new FavoritesFragment();
Bundle args = new Bundle();
args.putSerializable("all", recepies);
args.putBoolean("search", true);
args.putSerializable("cats", cats);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack("favorites").commit();
}
private void showMainFragment() {
Fragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putParcelableArrayList("all", recepies);
args.putSerializable("cats", cats);
args.putParcelableArrayList(Constants.MAINRECEPIES, mainRecepies);
args.putBoolean("search", true);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, fragment)
.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(sideWrapper))
mDrawerLayout.closeDrawer(sideWrapper);
else
mDrawerLayout.openDrawer(sideWrapper);
return true;
case R.id.main_action_fav:
showFavoritesFragment();
return true;
case R.id.main_action_choose_cats:
Intent intent = new Intent(this, CircleListActivity.class);
intent.putExtra(Constants.DEVICES_EXTRA, devices);
intent.putExtra("cats", cats);
startActivity(intent);
// finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initActionBar() {
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#e91a34")));
getActionBar().setCustomView(R.layout.actionbar_custom_view_home);
// actionBar.setcu
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(false);
getActionBar().setIcon(R.drawable.menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new SearchFragment();
Bundle args = new Bundle();
args.putString("cat-title", cats.get(position).getTitle());
args.putInt(Constants.CATEGORY_ID, cats.get(position).getId());
args.putSerializable("cats", cats);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).addToBackStack(null)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
// setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(sideWrapper);
}
@Override
public void setTitle(CharSequence title) {
// mTitle = title;
// getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
// mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
// mDrawerToggle.onConfigurationChanged(newConfig);
}
// This function gets the search results
public ArrayList<Recepie> getSearchResults(String keyword) {
ArrayList<Recepie> resultRecepie = new ArrayList<Recepie>();
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONObject jObj = jParser
.getJSONObjectFromUrl("http://oursson-recipes.outsourcingfarm.com/index.php/jsoner/getRecipe?query="
+ keyword);
try {
JSONArray withTechnics = jObj.getJSONArray("with_technics");
JSONArray withoutTechnics = jObj.getJSONArray("without_technics");
for (int i = 0; i < withTechnics.length(); i++) {
JSONObject with = withTechnics.getJSONObject(i);
boolean bool_tehcnics = true;
if (with.getInt("with_technics") == 1)
bool_tehcnics = false;
boolean my_devices = false;
if (with.getInt("mydevices") == 1)
my_devices = true;
JSONArray devices = with.getJSONArray("devices");
ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
for (int k = 0; k < devices.length(); k++) {
devicesIDs.add(Integer.valueOf(devices.getString(k)));
}
resultRecepie.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
}
for (int i = 0; i < withoutTechnics.length(); i++) {
JSONObject with = withoutTechnics.getJSONObject(i);
boolean bool_tehcnics = false;
if (with.getInt("with_technics") == 1)
bool_tehcnics = true;
boolean my_devices = false;
if (with.getInt("mydevices") == 1)
my_devices = true;
JSONArray devices = with.getJSONArray("devices");
ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
for (int k = 0; k < devices.length(); k++) {
devicesIDs.add(Integer.valueOf(devices.getString(k)));
}
resultRecepie.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
}
} catch (JSONException e) {
e.printStackTrace();
}
return resultRecepie;
}
}
这是一个片段(这是我从头开始的那个片段):
public class MainFragment extends Fragment {
private MainPhoneAdapter adapter;
private boolean search = false;
private ArrayList<Categories> cats;
private ArrayList<Recepie> recepies, mainRecepies;
private ArrayList<Recepie> withoTechnics;
private ArrayList<Recepie> wTechnics;
SharedPreferences prefs;
ImageView intro;
ProgressDialog dialog;
Animation animationFadeOut;
Display display;
public MainFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
Log.v("--", "main create");
if (Constants.isTablet(getActivity())) {
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
cats = (ArrayList<Categories>) getArguments().getSerializable("cats");
search = getArguments().getBoolean("search");
WindowManager wm = (WindowManager) getActivity().getSystemService(
Context.WINDOW_SERVICE);
display = wm.getDefaultDisplay();
prefs = getActivity().getSharedPreferences(
getActivity().getPackageName(), Context.MODE_PRIVATE);
initActionBar();
mainRecepies = new ArrayList<Recepie>();
recepies = new ArrayList<Recepie>();
wTechnics = new ArrayList<Recepie>();
withoTechnics = new ArrayList<Recepie>();
dialog = new ProgressDialog(getActivity());
if (getActivity().getIntent().getBooleanExtra("fromDevs", false)
&& search) {
dialog.setMessage("Loading..");
dialog.show();
parseJson(rootView);
} else {
recepies = getArguments().getParcelableArrayList("all");
mainRecepies = getArguments().getParcelableArrayList(
Constants.MAINRECEPIES);
Log.v("--", mainRecepies.size() + " MAiN SIZE");
// Log.v("--", "main frag" + recepies.size());
for (int i = 0; i < mainRecepies.size(); i++) {
if (mainRecepies.get(i).isWithTechnics())
wTechnics.add(mainRecepies.get(i));
else
withoTechnics.add(mainRecepies.get(i));
}
if (Constants.isTablet(getActivity())) {
populateViewForTablet(rootView);
populateWithouTechnicsTablet(rootView);
showAnimation(rootView);
} else
populateForPhones(rootView);
}
initImgLoader();
return rootView;
}
private void initActionBar() {
getActivity().getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#e91a34")));
getActivity().getActionBar().setCustomView(
R.layout.actionbar_custom_view_home);
// actionBar.setcu
getActivity().getActionBar().setDisplayShowTitleEnabled(false);
getActivity().getActionBar().setDisplayShowCustomEnabled(true);
getActivity().getActionBar().setDisplayUseLogoEnabled(false);
getActivity().getActionBar().setDisplayShowHomeEnabled(true);
getActivity().getActionBar().setNavigationMode(
ActionBar.NAVIGATION_MODE_STANDARD);
// getActivity().getActionBar().setHomeButtonEnabled(false);
// getActivity().getActionBar().setIcon(R.drawable.menu);
}
private void initImgLoader() {
ImageLoader.getInstance().init(
ImageLoaderConfiguration.createDefault(getActivity()));
}
private void showAnimation(View view) {
if (!prefs.getBoolean("main_shown", false)) {
prefs.edit().putBoolean("main_shown", true).commit();
startActivity(new Intent(getActivity(), Overlay.class));
getActivity().overridePendingTransition(R.anim.fadein,
R.anim.fadeout);
}
}
private void parseJson(final View rootView) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// add static ids from prefs as device ID's
String devs[] = prefs.getString(Constants.SELECTED_DEVICES,
"1,23,4").split(",");
int end = devs.length;
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < end; i++) {
set.add(Integer.valueOf(devs[i]));
}
String devicesUrl = "";
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
devicesUrl += it.next() + ",";
}
devicesUrl = devicesUrl.substring(0, devicesUrl.length() - 1);
Log.v("--", devicesUrl + " DV");
getJSONFromUrl("http://oursson-recipes.outsourcingfarm.com/index.php/jsoner/getRecipe?devices="
+ devicesUrl);
getMainScreenRecepies("http://oursson-recipes.outsourcingfarm.com/index.php/jsoner/getHome?devices="
+ devicesUrl);
return null;
}
protected void onPostExecute(Void result) {
// if TABLET
if (Constants.isTablet(getActivity())) {
populateViewForTablet(rootView);
populateWithouTechnicsTablet(rootView);
showAnimation(rootView);
} else
populateForPhones(rootView);
};
}.execute();
}
private void populateForPhones(View rootView) {
ListView gridView = (ListView) rootView.findViewById(R.id.main_grid);
adapter = new MainPhoneAdapter(getActivity(), wTechnics);
gridView.setAdapter(adapter);
if (dialog.isShowing())
dialog.dismiss();
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(),
FullScreenBanner.class);
intent.putExtra("cats", cats);
intent.putExtra(Constants.RECEPIES_EXTRA,
wTechnics.get(position));
intent.putExtra("fromMain", true);
intent.putExtra("recepieExtra", wTechnics.get(position).getId());
startActivity(intent);
}
});
}
private void populateViewForTablet(View rootView) {
withTest(rootView);
}
//
private void withTest(View rootView) {
LinearLayout parent = ((LinearLayout) rootView
.findViewById(R.id.main_parent));
Point size = new Point();
display.getSize(size);
int width = getActivity().getResources().getDisplayMetrics().widthPixels;
int height = (getActivity().getResources().getDisplayMetrics().heightPixels / 3) * 2;
for (int i = 0; i < 3; i++) {
final int position = i;
View r = LayoutInflater.from(getActivity()).inflate(
R.layout.main_item_gray, parent, false);
TextView top = (TextView) r
.findViewById(R.id.main_item_oursson_or_not);
top.setBackgroundResource(R.drawable.redtint);
ImageView itemBg = (ImageView) r.findViewById(R.id.main_item_img);
TextView title = (TextView) r.findViewById(R.id.main_item_title);
TextView time = (TextView) r.findViewById(R.id.main_item_time);
TextView persons = (TextView) r
.findViewById(R.id.main_item_persons);
String imgLink = wTechnics.get(i).getImage_1()
.replace("[HEIGHT]", height + "")
.replace("[WIDTH]", width / 3 + "");
title.setText(wTechnics.get(i).getTitle());
time.setText(wTechnics.get(i).getPreparation_time());
persons.setText(wTechnics.get(i).getPersons() + "");
ImageLoader.getInstance().displayImage(imgLink, itemBg);
parent.addView(r);
if (dialog.isShowing())
dialog.dismiss();
r.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
FullScreenBanner.class);
intent.putExtra(Constants.RECEPIES_EXTRA,
wTechnics.get(position));
intent.putExtra("cats", cats);
intent.putExtra("recepieExtra", wTechnics.get(position)
.getId());
startActivity(intent);
}
});
}
}
//
private void populateWithouTechnicsTablet(View rootView) {
LinearLayout parent = ((LinearLayout) rootView
.findViewById(R.id.main_without));
Point size = new Point();
display.getSize(size);
int width = getActivity().getResources().getDisplayMetrics().widthPixels;
int height = getActivity().getResources().getDisplayMetrics().heightPixels / 2;
for (int i = 0; i < 4; i++) {
final int position = i;
View r = LayoutInflater.from(getActivity()).inflate(
R.layout.main_item_gray_notfeatured, parent, false);
ImageView itemBg = (ImageView) r.findViewById(R.id.main_item_img);
TextView title = (TextView) r.findViewById(R.id.main_item_title);
TextView time = (TextView) r.findViewById(R.id.main_item_time);
TextView persons = (TextView) r
.findViewById(R.id.main_item_persons);
String imgLink = withoTechnics.get(i).getImage_1()
.replace("[HEIGHT]", height + "")
.replace("[WIDTH]", width / 4 + "");
title.setText(withoTechnics.get(i).getTitle());
time.setText(withoTechnics.get(i).getPreparation_time());
persons.setText(withoTechnics.get(i).getPersons() + "");
ImageLoader.getInstance().displayImage(imgLink, itemBg);
parent.addView(r);
if (dialog.isShowing())
dialog.dismiss();
r.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
FullScreenBanner.class);
intent.putExtra(Constants.RECEPIES_EXTRA,
withoTechnics.get(position));
intent.putExtra("cats", cats);
intent.putExtra("recepieExtra", withoTechnics.get(position)
.getId());
startActivity(intent);
}
});
}
}
public void getMainScreenRecepies(String url) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONObject jObj = jParser.getJSONObjectFromUrl(url);
try {
JSONArray withTechnics = jObj.getJSONArray("with_technics");
JSONArray withoutTechnics = jObj.getJSONArray("without_technics");
for (int i = 0; i < withTechnics.length(); i++) {
JSONObject with = withTechnics.getJSONObject(i);
mainRecepies.add(new Recepie(true, with.getInt("id"), with
.getInt("persons"), with.getString("title"), with
.getString("preparation_time"), with
.getString("image_1")));
}
for (int i = 0; i < withoutTechnics.length(); i++) {
JSONObject with = withoutTechnics.getJSONObject(i);
mainRecepies.add(new Recepie(false, with.getInt("id"), with
.getInt("persons"), with.getString("title"), with
.getString("preparation_time"), with
.getString("image_1")));
}
Log.v("--", "PARSED " + mainRecepies.size() + " " + url);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getJSONFromUrl(String url) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONObject jObj = jParser.getJSONObjectFromUrl(url);
Log.v("--", "asds");
try {
JSONArray withTechnics = jObj.getJSONArray("with_technics");
JSONArray withoutTechnics = jObj.getJSONArray("without_technics");
for (int i = 0; i < withTechnics.length(); i++) {
JSONObject with = withTechnics.getJSONObject(i);
boolean bool_tehcnics = false;
if (with.getInt("with_technics") == 1)
bool_tehcnics = true;
boolean my_devices = false;
if (with.getInt("mydevices") == 1)
my_devices = true;
JSONArray devices = with.getJSONArray("devices");
ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
for (int k = 0; k < devices.length(); k++) {
devicesIDs.add(Integer.valueOf(devices.getString(k)));
}
wTechnics.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
recepies.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
}
for (int i = 0; i < withoutTechnics.length(); i++) {
JSONObject with = withoutTechnics.getJSONObject(i);
boolean bool_tehcnics = false;
if (with.getInt("with_technics") == 1)
bool_tehcnics = true;
boolean my_devices = false;
if (with.getInt("mydevices") == 1)
my_devices = true;
JSONArray devices = with.getJSONArray("devices");
ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
for (int k = 0; k < devices.length(); k++) {
devicesIDs.add(Integer.valueOf(devices.getString(k)));
}
withoTechnics.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
recepies.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
}
Log.v("--", recepies.size() + " RS");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
使用newInstance方法可能会纠正两个片段的启动。广告文章当我查看片段示例时,我看到了很多newInstance代码。
public class MainFragment extends Fragment {
public static Fragment newInstance(int instance# pass in receipieces and cats here) {
MainFragment f = new MainFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putParcelableArrayList("all", recepies);
args.putSerializable("cats", cats);
args.putParcelableArrayList(Constants.MAINRECEPIES, mainRecepies);
args.putBoolean("search", true);
fragment.setArguments(args);
return f;
}
同时返回显示片段的活动,使用新实例启动片段。
private void showMainFragment() {
Fragment fragment = MainFragment.newInstacne(instance# pass in recipies and cats here);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, fragment)
.commit();
}