我正在尝试在 android 中创建一个主菜单活动,它从页面上的位置动态选择活动目标。
主菜单.java
package com.verscreative.BowlTrack;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class MainMenu extends SherlockActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new HomeMenuAdapter());
gridview.setPadding(50, 40, 50, 40);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Activities That are invoked by the click
String[] mActivitiesIds = {
getString(R.string.menu_launch_0),
getString(R.string.menu_launch_1),
getString(R.string.menu_launch_2),
getString(R.string.menu_launch_3),
getString(R.string.menu_launch_4),
getString(R.string.menu_launch_5)
};
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
//TODO: Switch Toast To Activity Intent
Intent i = new Intent();
i.setClassName(packageName, className);
try{
startActivity(i);
}catch(Exception e){
Toast t = Toast.makeText(getApplicationContext(), "Cannot Find Activity", Toast.LENGTH_LONG);
t.show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
activateSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void activateSettings(){
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
public class HomeMenuAdapter extends BaseAdapter {
public HomeMenuAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(getApplicationContext());
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setPadding(0, 10, 0, 10);
} else {
tv = (TextView) convertView;
}
tv.setCompoundDrawablesWithIntrinsicBounds(0, mThumbIds[position], 0, 0);
tv.setText(mTextIds[position]);
tv.setHeight(300);
tv.setTextColor(Color.WHITE);
return tv;
}
// references to our images
private Integer[] mThumbIds = {
android.R.drawable.ic_menu_add,
android.R.drawable.ic_menu_view,
android.R.drawable.ic_menu_info_details,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_preferences
};
private String[] mTextIds = {
getString(R.string.menu_item_0),
getString(R.string.menu_item_1),
getString(R.string.menu_item_2),
getString(R.string.menu_item_3),
getString(R.string.menu_item_4),
getString(R.string.menu_item_5)
};
}
}
但是,无论我做什么,它总是说“找不到活动”。
如果我改变:
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
Intent i = new Intent();
i.setClassName(packageName, className);
例如:
Context packageName = MainMenu.this;
Class<ViewGamesActivity> className = ViewGamesActivity.class;
Intent i = new Intent();
i.setClass(packageName, className);
它工作正常,但所有选项都做同样的事情!
字符串.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BowlTrack</string>
<string name="action_settings">Settings</string>
<string name="menu_item_0">Add New Game</string>
<string name="menu_item_1">View Games</string>
<string name="menu_item_2">Stats</string>
<string name="menu_item_3">3-Not</string>
<string name="menu_item_4">4-Not</string>
<string name="menu_item_5">Settings</string>
<string name="menu_launch_0">NewGameActivity</string>
<string name="menu_launch_1">ViewGamesActivity</string>
<string name="menu_launch_2">ViewOverallActivity</string>
<string name="menu_launch_3">3-Not</string>
<string name="menu_launch_4">4-Not</string>
<string name="menu_launch_5">SettingsActivity</string>
<color name="black">#000000</color>
<color name="bwtk">#88078b</color>
<string name="title_activity_view_games">View Games</string>
</resources>
ViewGamesActivity.java
package com.verscreative.BowlTrack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class ViewGamesActivity extends SherlockActivity {
public class ViewGames extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static final String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_games);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
// TODO: Starting new intent
// Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
// in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response
// back
// startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGamesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// TODO: no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewGamesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME }, new int[] { R.id.pid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}