因此,我被分配使用隐式意图打开带有“股票代码”的浏览器。股票代码只是 URL 的扩展,如下面的代码所示。当我单击按钮输入 url 时,股票代码会被存储为共享首选项并添加到选项菜单中。我可以访问选项菜单并从菜单中打开一个 URL,问题是如果我不断单击菜单按钮,即使它已经存在,它也会添加 menuItem。我尝试使用 contains 方法,但它从未出错,所以我必须错误地存储首选项?任何帮助都会很棒!
package com.example.sharedpreferences;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText edit;
String StockTicker;
SharedPreferences.Editor editor;
public static String MY_PREFS = "edu.college.ece3233.my_prefs";
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= (EditText)findViewById(R.id.MyText);
prefs = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE);
editor = prefs.edit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menu.clear();
return true;
}
public void SharedPreferenceClick(View view){
StockTicker=edit.getText().toString();
Intent intent =new Intent(Intent.ACTION_VIEW,Uri.parse("http://finance.yahoo.com/q?s="+ StockTicker));
startActivity(intent);
editor.putString("StockTick", StockTicker);
editor.commit();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu){
if(!prefs.contains(prefs.getString("StockTick", "")))
menu.add(prefs.getString("StockTick", ""));
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent2 =new Intent(Intent.ACTION_VIEW,Uri.parse("http://finance.yahoo.com/q?s="+ item.toString()));
startActivity(intent2);
return super.onOptionsItemSelected(item);
}
}