如何从另一个Activity

时间:2017-05-27 03:59:35

标签: java android

我有一个名为ArrayList的{​​{1}},它是在应用程序启动时创建的,并通过多种方法填充数据。这个refineList用于自定义List,它根据Adapter数据加载不同的内容。

我有几种方法可以重新排列refineListrefineList内部,但在其中一种情况下,我通过MainActivity开始新的Activity(通过重写方法Intent)和新onRightCardExit()我有一个按钮,用户按下后我想重新排列Activity中的refineList

我已在我的MainActivityMainActivity)中创建了该方法,但如何从其他refineListWithSimular()调用该方法,是否有更好的解决方案?我读到了在Utility类中移动这种方法,但我没有弄清楚如何使用它。

以下是我的Activity

MainActivity

这是我的另一个名为package com.botevplovdiv.foodmatch2; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.os.Bundle; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.SwitchPreference; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Toast; import com.bumptech.glide.Glide; import com.lorentzos.flingswipe.SwipeFlingAdapterView; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class MainActivity extends AppCompatActivity { // keys for reading data from SharedPreferences public static final String FISH = "fishSwitch"; public static final String MEAT = "meatSwitch"; public static final String VEGETARIAN = "vegSwitch"; public static final String PIZZA = "pizzaSwitch"; public static final String PASTA = "pastaSwitch"; public static final String RESTAURANTS = "restaurantSwitch"; public static final String TAKEAWAY = "takeAwaySwitch"; private MyAppAdapter myAppAdapter; private List<FoodDish> dishList; private List<FoodDish> refineList; private List<FoodDish> dumpList; private List<Venue> venues; private boolean[] booleans; private String[] booleansTags; private List<String> searchCriteria; private SwipeFlingAdapterView flingContainer; public static Map<String, Bitmap> bitmaps = new HashMap<>(); boolean fishSwitch; boolean meatSwitch; boolean vegetarianSwitch; boolean pizzaSwitch; boolean pastaSwitch; boolean restaurantSwitch; boolean takeAwaySwitch; boolean preferenceChanged = true; public final static String TAG = "FoodMatch"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Log.i(TAG,"Entered onCreate() method in MainActivity"); flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame); // set default values in the app's SharedPreferences PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // register listener for SharedPreferences changes SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.registerOnSharedPreferenceChangeListener( preferencesChangeListener); fishSwitch = sharedPreferences.getBoolean(FISH,false); meatSwitch = sharedPreferences.getBoolean(MEAT,false); vegetarianSwitch = sharedPreferences.getBoolean(VEGETARIAN,false); pizzaSwitch = sharedPreferences.getBoolean(PIZZA,false); pastaSwitch = sharedPreferences.getBoolean(PASTA,false); restaurantSwitch = sharedPreferences.getBoolean(RESTAURANTS,false); takeAwaySwitch = sharedPreferences.getBoolean(TAKEAWAY,false); booleansTags = new String[] {"FISH","MEAT","VEGETARIAN","PIZZA","PASTA","RESTAURANT","TAKE AWAY"}; dishList = new ArrayList<>(); searchCriteria = new ArrayList<>(); refineList = new ArrayList<>(); dumpList = new ArrayList<>(); // load initial data loadDishes(); createSearchCriteria(searchCriteria); refineDishesList(); //lock the device to portrait mode setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); myAppAdapter = new MyAppAdapter(this, refineList); flingContainer.setAdapter(myAppAdapter); flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() { @Override public void removeFirstObjectInAdapter() { } @Override public void onLeftCardExit(Object dataObject) { FoodDish current = refineList.get(0); refineList.remove(0); myAppAdapter.notifyDataSetChanged(); if (refineList.isEmpty()){ if (checkSwitches()){ showRestartDialog(); }else{ Toast.makeText(MainActivity.this,"The combination of switches turned off, won`t show any results",Toast.LENGTH_SHORT).show(); } } //Do something on the left! //You also have access to the original object. //If you want to use it just cast it (String) dataObject } @Override public void onRightCardExit(Object dataObject) { FoodDish current = refineList.get(0); Intent intent = new Intent(MainActivity.this,LikedProduct.class).putExtra("current",current); startActivity(intent); refineList.remove(0); myAppAdapter.notifyDataSetChanged(); } @Override public void onAdapterAboutToEmpty(int itemsInAdapter) { } @Override public void onScroll(float scrollProgressPercent) { View view = flingContainer.getSelectedView(); view.findViewById(R.id.background).setAlpha(0); view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0); view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0); } }); // Listener for touching events flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() { @Override public void onItemClicked(int itemPosition, Object dataObject) { View view = flingContainer.getSelectedView(); view.findViewById(R.id.background).setAlpha(0); Toast toast = Toast.makeText(MainActivity.this,"test",Toast.LENGTH_SHORT); toast.show(); myAppAdapter.notifyDataSetChanged(); } }); //floating buttons for remote flipping the cards FloatingActionButton yesFAB = (FloatingActionButton) findViewById(R.id.acceptButton); yesFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!refineList.isEmpty()) flingContainer.getTopCardListener().selectRight(); } }); FloatingActionButton noFAB = (FloatingActionButton) findViewById(R.id.rejectButton); noFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!refineList.isEmpty()) flingContainer.getTopCardListener().selectLeft(); } }); } @Override protected void onResume() { super.onResume(); Log.i(TAG,"Entered onResume() method in MainActivity"); if (refineList.isEmpty()){ if (checkSwitches()){ showRestartDialog(); }else{ Toast.makeText(MainActivity.this,"The combination of switches turned off, will not return any results",Toast.LENGTH_LONG).show(); } } } private void refineDishesList() { if (this.refineList.size() > 0) { this.refineList.clear(); } for (FoodDish dish : this.dishList){ if (this.searchCriteria.contains(dish.getCategory().toUpperCase()) && this.searchCriteria.contains(dish.getVenueType().toUpperCase())){ this.refineList.add(dish); } } } private void createSearchCriteria(List<String> searchCriteria){ booleans = new boolean[]{fishSwitch,meatSwitch,vegetarianSwitch,pizzaSwitch,pastaSwitch,restaurantSwitch,takeAwaySwitch}; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (searchCriteria.size() >0){ searchCriteria.clear(); } for (int i = 0;i < booleansTags.length;i++){ boolean temp = booleans[i]; if (temp){ searchCriteria.add(booleansTags[i]); } } } private boolean checkSwitches(){ boolean check = true; if ((!fishSwitch && !meatSwitch && !vegetarianSwitch && !pizzaSwitch && !pastaSwitch) || (!restaurantSwitch && !takeAwaySwitch)){ check = false; } return check; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent preferencesIntent = new Intent(this, Settings.class); startActivity(preferencesIntent); return super.onOptionsItemSelected(item); } public void loadDishes(){ dishList.add(new FoodDish("Shrimp dish","https://cdn.pixabay.com/photo/2015/04/10/00/41/food-715539_960_720.jpg",getString(R.string.test),"Price : 2,14", "FISH","Restaurant")); dishList.add(new FoodDish("Pizza ultra mega qkata rabota","http://www.seattleorganicrestaurants.com/vegan-whole-foods/images/Food-Guidelines.jpg","Test description.This a very tasty dish and you should definitely order it.I don`t know what are you waiting for", "Price: 3,87", "PIZZA","Take Away")); dishList.add(new FoodDish("Pasta","http://assets.simplyrecipes.com/wp-content/uploads/2008/03/pasta-tuna-arugula-horiz-a-1600.jpg",getString(R.string.test), "Price: 4,87","PASTA","Restaurant")); dishList.add(new FoodDish("Chicken wings","http://cf.yellowblissroad.com/wp-content/uploads/2015/02/Baked-Chicken-Wings.jpg",getString(R.string.test),"Price: 1,23","MEAT","Take Away")); dishList.add(new FoodDish("Fish","http://cdn.skim.gs/image/upload/v1456339187/msi/grilled-catfish_izglgf.jpg",getString(R.string.test), "Price: 5,87", "FISH","Take Away")); dishList.add(new FoodDish("Spaghetti","http://food.fnr.sndimg.com/content/dam/images/food/fullset/2009/6/12/2/FO1D41_23785_s4x3.jpg.rend.hgtvcom.616.462.jpeg",getString(R.string.test), "Price: 9,23", "PASTA","Restaurant")); dishList.add(new FoodDish("Ceasar salad","http://entomofarms.com/wp-content/uploads/2016/04/EF-caesar-salad-cricket-powder.jpg",getString(R.string.test), "Price: 3,45", "VEGETARIAN","Restaurant")); dishList.add(new FoodDish("Steak sandwich","http://s3.amazonaws.com/finecooking.s3.tauntonclud.com/app/uploads/2017/04/18125307/051120015-01-steak-sandwich-recipe-main.jpg",getString(R.string.test), "Price: 3,45","MEAT","Take Away")); dishList.add(new FoodDish("Lasagna","http://www.weightlossresources.co.uk/img/recipes/vegetarian-dishes.jpg",getString(R.string.test), "Price: 11,45","VEGETERIAN","Restaurant")); dishList.add(new FoodDish("Sea Food Risotto","http://www.dvo.com/recipe_pages/healthy/Lemony_Seafood_Risotto.jpg",getString(R.string.test), "Price: 8,45","VEGETERIAN","Take Away")); } public void refreshContent(){ createSearchCriteria(searchCriteria); refineDishesList(); flingContainer.removeAllViewsInLayout(); myAppAdapter.notifyDataSetChanged(); preferenceChanged = true; } public void refineListWithSimilar(String simularCategory){ if (this.refineList.size()>0){ for (FoodDish dish : this.refineList){ if (dish.getCategory().toUpperCase().equals(simularCategory.toUpperCase())){ this.refineList.add(0,dish); }else{ this.refineList.add(dish); } } } flingContainer.removeAllViewsInLayout(); myAppAdapter.notifyDataSetChanged(); } public void showRestartDialog(){ new AlertDialog.Builder(MainActivity.this) .setTitle("Restart list?") .setMessage("Do you want to restart the list?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { createSearchCriteria(searchCriteria); refineDishesList(); myAppAdapter.notifyDataSetChanged(); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } private SharedPreferences.OnSharedPreferenceChangeListener preferencesChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { switch (key){ case FISH: fishSwitch = sharedPreferences.getBoolean(FISH,false); refreshContent(); break; case MEAT: meatSwitch = sharedPreferences.getBoolean(MEAT,false); refreshContent(); break; case VEGETARIAN: vegetarianSwitch = sharedPreferences.getBoolean(VEGETARIAN,false); refreshContent(); break; case PIZZA: pizzaSwitch = sharedPreferences.getBoolean(PIZZA,false); refreshContent(); break; case PASTA: pastaSwitch = sharedPreferences.getBoolean(PASTA,false); refreshContent(); break; case RESTAURANTS: restaurantSwitch = sharedPreferences.getBoolean(RESTAURANTS,false); refreshContent(); break; case TAKEAWAY: takeAwaySwitch = sharedPreferences.getBoolean(TAKEAWAY,false); refreshContent(); break; } //end of switch statement } }; } 的{​​{1}}。基本上,我想在单击Activity按钮时调用方法来重新排列LikedProduct中的refineList。

viewSimular

提前感谢您的帮助。

更新

我看到我的问题被标记为重复,但另一个问题与我的问题没有任何共同之处。我问我如何在返回之前重新安排MainActivitypackage com.botevplovdiv.foodmatch2; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.target.Target; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class LikedProduct extends AppCompatActivity { Button smallBackButton; Button viewSimilar; String TAG = "FoodMatch"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_liked_product); final FoodDish current = getIntent().getExtras().getParcelable("current"); Glide .with(getApplicationContext()) .load(current.getImagePath()) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL) { @Override public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) { ImageView image = (ImageView) findViewById(R.id.likedImagePic); image.setImageBitmap(resource); } }); viewSimilar = (Button) findViewById(R.id.view_similar); viewSimilar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String similarCategory = current.getCategory(); //Here I want to use the method to rearrange the refineList and then go back to MainActivity onBackPressed(); } }); smallBackButton = (Button) findViewById(R.id.smallBackButton); smallBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } @Override protected void onStart() { super.onStart(); Log.i(TAG,"Entered onStart() method in LikedProduct"); } } 来自另一项活动。

我设法使用ArrayList找到了一些解决方案,但我问的是如何访问MainActivity中的列表或方法,因为我想在重新排列列表之前重新排列它。根据我的阅读,其中一个选项是制作方法startActivityForResult,但我也必须制作MainActivity static。这是一个很好的做法,有没有做到这一点的缺陷?

1 个答案:

答案 0 :(得分:-1)

您可以使用Application类将其存档,如下所示:

public class MyApplication extends Application{
     private List<YourObject> refineList;
}

然后您可以随时随地修改refineList((MyApplication)getApplication()).getRefineList();