模仿操作栏上的后退按钮

时间:2018-02-22 15:32:37

标签: java android menu

所以我有一个操作栏后退按钮,它将我从一个活动返回到我的主要活动。我遇到的问题是,当你按下操作栏后退按钮时,它会调用loadData()(从API加载数据)。

如果我按下设备上的后退按钮(主页按钮旁边的按钮),我将返回上一个视图(主要活动),并且不必再次调用API。

所以我试图找到一种模仿物理后退按钮作为操作栏小部件的方法。

我不希望再次调用MainActivity的代码,因为它会执行另一个API调用(我每分钟只能有5个),而且速度也慢一些。我只是想让它回到我刚才的观点。

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<ListItem> listItems;
private String defaultQuery = "ham";
private String builtURL;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    listItems = new ArrayList<>();

    loadData(defaultQuery);
}

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            listItems.clear();
            loadData(query);
            (menu.findItem(R.id.action_search)).collapseActionView();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
    searchView.setIconified(false);
    return true;
}

public void loadData(String query) {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading recipes...");
    progressDialog.show();
    Log.d("q", "loadData: " + query);
    builtURL = buildURL(query);

    StringRequest request = new StringRequest(Request.Method.GET,
            builtURL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    progressDialog.dismiss();
                    if(response == null) {
                        response = "THERE WAS AN ERROR";
                    }
                    try {
                        JSONObject obj = new JSONObject(response);
                        JSONArray hits = obj.getJSONArray("hits");
                        for (int i = 0; i < hits.length(); i++) {
                            JSONObject a = hits.getJSONObject(i);
                            JSONObject recipe = a.getJSONObject("recipe");
                            String ingredients = recipe.getString("ingredientLines");
                            ingredients = ingredients.replace("[", "");
                            ingredients = ingredients.replace("]", "");
                            ingredients = ingredients.replace("\"", "");
                            ingredients = ingredients.replace("\\", "");
                            ingredients = ingredients.replace(",", "\n");
                            ListItem item = new ListItem(
                                    recipe.getString("label"),
                                    recipe.getString("source"),
                                    recipe.getString("image"),
                                    ingredients,
                                    recipe.getString("url")
                            );
                            listItems.add(item);
                        }

                        adapter = new Adapter(listItems, getApplicationContext(), builtURL);
                        recyclerView.setAdapter(adapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue rq = Volley.newRequestQueue(this);
    rq.add(request);
}



private String buildURL(String query) {
    Log.d("q", "buildURL: " + query);
    Uri.Builder builder = new Uri.Builder();
    //url built here but I removed it because it shows API key etc.

    String urlToSend = builder.build().toString();
    //debugging purposes to show the url created
    Log.d("url", "doInBackground: " + urlToSend);

    return urlToSend;
}

@Override
public boolean onNavigateUp(){
    finish();
    return true;
}

这是我来自的活动。

public class recipe_view extends AppCompatActivity {

ImageView ivRecipeImage;
TextView tvRecipeName;
TextView tvRecipeCreator;
TextView tvRecipeIngredients;
String url;
Integer pos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recipe_view);

    Bundle data = getIntent().getExtras();
    ArrayList<ListItem> list = data.getParcelableArrayList("list");
    pos = data.getInt("pos");
    for (int i = 0; i < list.size() ; i++) {
        System.out.println(list.get(i));
        System.out.println(pos);
    }
    ivRecipeImage = findViewById(R.id.recipeImage);
    tvRecipeName = findViewById(R.id.recipeName);
    tvRecipeCreator = findViewById(R.id.recipeCreator);
    tvRecipeIngredients = findViewById(R.id.ingredients);

    tvRecipeName.setText(list.get(pos).getTitle());
    tvRecipeCreator.setText(list.get(pos).getAuthor());
    Picasso.with(getApplicationContext())
            .load(list.get(pos).getImageUrl())
            .centerCrop()
            .fit()
            .into(ivRecipeImage);
    tvRecipeIngredients.setText(list.get(pos).getListOfIngredients());
    url = list.get(pos).getRecipeUrl();

    final Button button = findViewById(R.id.bViewInstructions);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(goToBrowser);
        }
    });
}
}

2 个答案:

答案 0 :(得分:0)

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(goToBrowser);
            finish();
        }
    });

答案 1 :(得分:0)

在你的清单xml中

<activity
android:name=".your_activity"
android:label="@string/title_activity_sign_up"
android:parentActivityName=".whateveractivity"
android:screenOrientation="portrait" >
</activity>

然后在代码中

@Override
public void onBackPressed() {
    NavUtils.navigateUpFromSameTask(this); 
    // Otherwise defer to system default behavior.
    super.onBackPressed(); 
}

详细说明您正在做的是覆盖onbackpressed硬件按钮。

同时使您的父活动的launchmode为singleInstance。