2014-01-27 32 views
0

我有一個列表視圖與圖像的儲物櫃以及。Android:無法實現列表視圖中的圖像視圖的點擊監聽器

在列表視圖中的每一行,有一個圖像和數據:在該列表視圖

我有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

希望這個解決方案是你所需要的。

的接口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); 
      } 
      } 
     }); 
    } 
} 
+0

嗨我需要創建一個新的SimpleAdapter.java類,因爲我做了先前不這樣做 – user3238961

+0

你可以看到更多:https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/ – Luc

0

你可以在適配器類的imageview上應用「onclicklistner」,並在listview的其他部分應用相同的東西..這可能會解決你的問題

相關問題