我也有一个带图像的储物柜列表视图。
在列表视图的每一行中,都有一张图片和数据:
我在此列表视图中有 OnItemClickListener 。
我已经阅读了很多stackoverflow网站,但我仍然不确定如何执行: 单击ImageView启动MapsActivity,否则单击ListItem上的任何其他位置启动StopsScheduleActivity。
我不确定如何仅根据我的代码为我的图像实现onclick监听器:
MainActivity.java
public class MainActivity extends Activity {
// Used to make the URL to call for JSON data
String yahooURLFirst = "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22";
String yahooURLSecond =
"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
String stockSymbol = "MSFT";
// Will hold the values I pull from the JSON
static String stockDaysLow = "";
static String stockDaysHigh = "";
static String stockYearLow = "";
static String stockYearHigh = "";
static String stockLastPrice = "";
static String stockChange = "";
static String stockDailyPriceRange = "";
// Array of strings storing country names
String[] countries = new String[] { "India", "Pakistan", "Sri Lanka",
"China", "Bangladesh", "Nepal", "Afghanistan", "North Korea",
"South Korea", "Japan" };
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[] { R.drawable.india, R.drawable.pakistan,
R.drawable.srilanka, R.drawable.china, R.drawable.bangladesh,
R.drawable.nepal, R.drawable.afghanistan, R.drawable.nkorea,
R.drawable.skorea, R.drawable.japan };
// Array of strings to store currencies
String[] currency = new String[] { "SIS", "SOE/SOSS", "SOA/SOL", "LKCSB",
"Bangladeshi Taka", "Nepalese Rupee", "Afghani",
"North Korean Won", "South Korean Won", "Japanese Yen" };
// Array of strings to store currencies
String[] size = new String[] { "Small", "Medium", "Large", "Small",
"Medium", "Large", "Small", "Medium", "Large", "Small" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creates the window used for the UI
setContentView(R.layout.main2);
// Create the YQL query
final String yqlURL = yahooURLFirst + stockSymbol + yahooURLSecond;
// final String yqlURL2
// ="http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%
20in%20(%22msft%22)&format=json&env=
store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
new MyAsyncTask().execute(yqlURL);
}
MyAsyncTask 类
private class MyAsyncTask extends AsyncTask<String, Void, List<String>> {
@Override
// protected String doInBackground(String... arg0) {
protected List<String> doInBackground(String... arg0) {
List<String> returnList = new ArrayList<String>();
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(arg0[0]);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the
// Buffer is full
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"),
8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer until nothing is left
while ((line = reader.readLine()) != null) {
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the InputStream when you're done with it
try {
if (inputStream != null)
inputStream.close();
} catch (Exception e) {
}
}
// Holds Key Value pairs from a JSON source
JSONObject jsonObject;
try {
// Print out all the data read in
// Log.v("JSONParser RESULT ", result);
// Get the root JSONObject
jsonObject = new JSONObject(result);
// Get the JSON object named query
JSONObject queryJSONObject =
jsonObject.getJSONObject("query");
JSONObject resultsJSONObject = queryJSONObject
.getJSONObject("results");
JSONObject quoteJSONObject = resultsJSONObject
.getJSONObject("quote");
// Get the JSON Strings in the quote object
stockSymbol = quoteJSONObject.getString("symbol");
stockDaysLow = quoteJSONObject.getString("DaysLow");
stockDaysHigh = quoteJSONObject.getString("DaysHigh");
stockYearLow = quoteJSONObject.getString("YearLow");
stockYearHigh = quoteJSONObject.getString("YearHigh");
stockLastPrice = quoteJSONObject
.getString("LastTradePriceOnly");
stockChange = quoteJSONObject.getString("Change");
stockDailyPriceRange = quoteJSONObject.getString
("DaysRange");
returnList.add(stockSymbol);
returnList.add(stockDaysLow);
returnList.add(stockDaysHigh);
returnList.add(stockYearLow);
returnList.add(stockYearHigh);
returnList.add(stockLastPrice);
returnList.add(stockChange);
returnList.add(stockDailyPriceRange);
returnList.add(stockDaysHigh);
returnList.add(stockDaysHigh);
// EXTRA STUFF THAT HAS NOTHING TO DO WITH THE PROGRAM
Log.v("SYMBOL ", stockSymbol);
Log.v("Days Low ", stockDaysLow);
Log.v("Days High ", stockDaysHigh);
Log.v("stockYearLow ", stockYearLow);
Log.v("stockYearHigh ", stockYearHigh);
Log.v("stockLastPrice ", stockLastPrice);
Log.v("stockChange ", stockChange);
Log.v("stockDailyPriceRange ", stockDailyPriceRange);
// GET ARRAY DATA
JSONArray queryArray = quoteJSONObject.names();
List<String> list = new ArrayList<String>();
for (int i = 0; i < queryArray.length(); i++) {
list.add(queryArray.getString(i));
}
for (String item : list) {
Log.v("JSON ARRAY ITEMS ", item);
}
// END OF GET ARRAY DATA
// Gets the first item in the JSONObject
JSONArray objectArray = resultsJSONObject.names();
// Prints out that first item in the JSONObject
Log.v("JSON NEXT NODE ", objectArray.getString(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return result;
return returnList;
}
protected void onPostExecute(List<String> returnList) {
// Each row in the list stores country name, currency and flag
List<HashMap<String, String>> aList = new ArrayList<HashMap<String,
String>>();
for (int i = 0; i < 10; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
// hm.put("txt", "Locker No : " + resultList.get(i));
hm.put("txt", "Locker No : " + i);
hm.put("cur", "Location : " + returnList.get(i));
hm.put("size", "Size : " + size[i]);
hm.put("flag", Integer.toString(flags[i]));
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag", "txt", "cur", "size" };
// Ids of views in listview_layout
int[] to = { R.id.flag, R.id.txt, R.id.cur, R.id.size };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = (ListView) findViewById(R.id.androidlist);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this,
"You Clicked at " + size[+position],
Toast.LENGTH_SHORT).show();
}
});
}
}
}
布局 main2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/butt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="@string/button" >
</Button>
<ListView
android:id="@+id/androidlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/butt1"
android:layout_below="@+id/textView2"
android:layout_marginBottom="2dip"
android:layout_marginTop="2dip"
android:drawSelectorOnTop="false"
android:visibility="visible" />
</RelativeLayout>
布局 listview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<TextView
android:id="@+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
/>
<TextView
android:id="@+id/size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
/>
</LinearLayout>
</LinearLayout>
请帮助,我一直在寻找答案,但无法找到
答案 0 :(得分:0)
希望这个解决方案是您所需要的。
界面 OnImageClickListener
public interface OnImageClickListener {
public void onClick(View view, Object data); // Object data [Optional]
}
在 MainActivity
上public class MainActivity extends Activity implements OnImageClickListener {
//... Your code
public void inSomeMethod() {
// Assume that you create an Adapter here.
new SimpleAdapter(this, ....).execute(...);
}
@Override
public void onClick(View view, Object data) {
// Handle image click here
}
}
在适配器
上public class SimpleAdapter extends ArrayAdapter<Param, Progress, Result> {
private OnImageClickListener mListener;
public SimpleAdapter(OnImageClickListener listener, ...) {
this.mListener = listener;
}
public View getView(....) {
ImageView imageView = (ImageView) view.findViewById(R.id.your_img_view);
imageView.setOnClickListener(new OnClickLisnter{ // I am not sure OnClickListener because I'm using notepad to write this code.
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onClick(v, dataIfYouWantToAttach);
}
}
});
}
}
答案 1 :(得分:0)
你可以在适配器类的imageview上应用“onclicklistener”,并在listview的其他部分应用相同的东西......这可能会解决你的问题