2015-05-25 2 views
0

Код ниже прекрасно работает в ListView, и я потратил несколько дней, пока не понял, как преобразовать его в GridView. Сначала я пытаюсь заменить ListView на GridView, но не удалось. Кто-нибудь может помочь?Android конвертировать список в GridView

+0

код не отправлен ... – Jim

+0

Вы забыли прикрепить код! –

+1

404: Код не найден. –

ответ

0
package com.betech.bbqv2.jsonparse; 
import android.app.ActionBar; 

import com.betech.bbqv2.login.AndroidPHPConnectionDemo; 
import com.betech.bbqv2.main.AddActivity; 
import com.betech.bbqv2.main.CheckLogin; 
import com.betech.bbqv2.main.DataListView; 
import com.betech.bbqv2.main.MainActivity; 
import com.betech.bbqv2.main.OrderHistory; 
import com.betech.bbqv2.R; 
import com.betech.bbqv2.main.SingleContactActivity; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.HashMap; 
import java.util.List; 

import org.json.JSONObject; 

import android.app.ActionBar; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.Window; 
import android.view.WindowManager; 
import android.widget.AdapterView; 
import android.widget.Button; 
import android.widget.GridView; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.widget.AdapterView.OnItemClickListener; 

public class countrymain extends Activity { 

ListView mListView; 
private String catid; 
private String companycode="bbq"; 

private SharedPreferences loginPreferences; 
private SharedPreferences.Editor loginPrefsEditor; 

private SharedPreferences tmploginPreferences; 
private SharedPreferences.Editor tmploginPrefsEditor; 
String matchguest=""; 

private ActionBar actionBar; 
@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    // requestWindowFeature(Window.FEATURE_NO_TITLE); 
    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 

    setContentView(R.layout.country_main); 
    actionBar = getActionBar(); 
    actionBar.show(); 
    getActionBar().setIcon(R.drawable.actionbar_icon); 
    getActionBar().setDisplayShowTitleEnabled(false); 


    loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE); 
    loginPrefsEditor = loginPreferences.edit(); 
    tmploginPreferences = getSharedPreferences("tmploginPrefs", MODE_PRIVATE); 
    tmploginPrefsEditor = tmploginPreferences.edit(); 
     String login1 = loginPreferences.getString("username", ""); 
     String login2 = tmploginPreferences.getString("tmpusername", ""); 
     String match="nomatch"; 
     login1=login1.toLowerCase(); 
     login2=login2.toLowerCase(); 


     if(login1.equalsIgnoreCase("guest") || login2.equalsIgnoreCase("guest")){ 

      matchguest="guest"; 

     }else{ 
      matchguest="noguest"; 
     } 

    catid=getIntent().getExtras().getString("cat"); 
    String strUrl = "http://myweb/bbq/mobile.php?catid="+catid+"&matchguest="+matchguest; 



    DownloadTask downloadTask = new DownloadTask(); 

    // Starting the download process 
    downloadTask.execute(strUrl); 

    // Getting a reference to ListView of activity_main 
    mListView = (ListView) findViewById(R.id.lv_countries); 
    mListView.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 
     //Open the browser here 

      HashMap<String,Object> map = (HashMap<String, Object>) parent.getItemAtPosition(position);  
      TextView foodcode = ((TextView) mListView.findViewById(R.id.foodcode)); 
      TextView foodname = ((TextView) mListView.findViewById(R.id.foodname)); 
      TextView fooddesc1 = ((TextView) mListView.findViewById(R.id.fooddesc1)); 
      TextView fooddesc2 = ((TextView) mListView.findViewById(R.id.fooddesc2)); 
      TextView foodprice = ((TextView) mListView.findViewById(R.id.foodprice)); 


     // Toast.makeText(countrymain.this, "label is="+map.get("country") 
       // , Toast.LENGTH_SHORT).show(); 
     // Toast.makeText(countrymain.this, "label is="+quantity.getText().toString() 
        //, Toast.LENGTH_SHORT).show(); 
      //TextView quantity = ((TextView) v.findViewById(R.id.value)); 



      Intent in = new Intent(getApplicationContext(), 
        SingleContactActivity.class); 
      in.putExtra("foodcode", map.get("foodcode").toString()); 
      in.putExtra("foodname", map.get("foodname").toString()); 
      in.putExtra("fooddesc1", map.get("fooddesc1").toString()); 
      in.putExtra("fooddesc2", map.get("fooddesc2").toString()); 
      in.putExtra("foodprice", map.get("foodprice").toString()); 
      in.putExtra("imagepath", map.get("flag_path").toString()); 

      startActivity(in); 

    } 
    }); 

    // public void onItemClick(AdapterView<?> parent, View v, 
    //  int position, long id) { 
    // mListView.setOnItemClickListener(new OnItemClickListener() { 

    // public void onItemClick(AdapterView adapterView, View view, int position, long id) { 
     // SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter(); 
     // ListView currentLv = (ListView) view; 

      // Object item = adapter.getItem(position); 
      //Do some more stuff here and launch new activity 


      //} 
     //}); 


} 

/** A method to download json data from url */ 
private String downloadUrl(String strUrl) throws IOException{ 
    String data = ""; 
    InputStream iStream = null; 
    try{ 
      URL url = new URL(strUrl); 

      // Creating an http connection to communicate with url 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

      // Connecting to url 
      urlConnection.connect(); 

      ///////////////////////////////Newly added 
      int responseCode = urlConnection.getResponseCode(); 
      String responseMessage = urlConnection.getResponseMessage(); 

      // InputStream is = null; 
      Log.d("response code=",String.valueOf(responseCode)); 
      if (responseCode >= 400) { 
       iStream = urlConnection.getErrorStream(); 
      } else { 
       //is = urlConnection.getInputStream(); 
       iStream = urlConnection.getInputStream(); 
      } 

      ///////////////////////////////////////////////// 

      // Reading data from url 
      // iStream = urlConnection.getInputStream();<---original 

      BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

      StringBuffer sb = new StringBuffer(); 

      String line = ""; 
      while((line = br.readLine()) != null){ 
       sb.append(line); 
      } 

      data = sb.toString(); 

      br.close(); 

    }catch(Exception e){ 
      Log.d("Exception while downloading url", e.toString()); 
    }finally{ 
      iStream.close(); 
    } 

    return data; 
} 



/** AsyncTask to download json data */ 
private class DownloadTask extends AsyncTask<String, Integer, String>{ 
    String data = null; 
      @Override 
      protected String doInBackground(String... url) { 
        try{ 
         data = downloadUrl(url[0]); 


        }catch(Exception e){ 
         Log.d("Background Task",e.toString()); 
        } 
        return data; 
      } 

      @Override 
      protected void onPostExecute(String result) { 

        // The parsing of the xml data is done in a non-ui thread 
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask(); 

        // Start parsing xml data 
        listViewLoaderTask.execute(result);       

      } 
} 

/** AsyncTask to parse json data and load ListView */ 
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{ 

    JSONObject jObject; 

    // Doing the parsing of xml data in a non-ui thread 
    @Override 
    protected SimpleAdapter doInBackground(String... strJson) { 


     try{ 

      //Toast.makeText(countrymain.this, "URL="+strJson[0], Toast.LENGTH_SHORT).show(); 
      jObject = new JSONObject(strJson[0]); 




      CountryJSONParser countryJsonParser = new CountryJSONParser(); 
      countryJsonParser.parse(jObject); 
     }catch(Exception e){ 
      Log.d("JSON Exception1",e.toString()); 
     } 

     // Instantiating json parser class 
     CountryJSONParser countryJsonParser = new CountryJSONParser(); 

     // A list object to store the parsed countries list 
     List<HashMap<String, Object>> countries = null; 

     try{ 
      // Getting the parsed data as a List construct 
      countries = countryJsonParser.parse(jObject); 
     }catch(Exception e){ 
      Log.d("Exception",e.toString()); 
     }   

     // Keys used in Hashmap 
     //String[] from = { "country","flag","details"}; 
     String[] from = { "foodcode","foodname","fooddesc1","fooddesc2","foodprice","flag"}; 

     // Ids of views in listview_layout 
     // int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details}; 
     int[] to = { R.id.foodcode,R.id.foodname,R.id.fooddesc1, R.id.fooddesc2,R.id.foodprice,R.id.iv_flag}; 

     // Instantiating an adapter to store each items 
     // R.layout.listview_layout defines the layout of each item   
     SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to); 


    // CheckLogin checknow = new CheckLogin(); 

    // String guestnot=checknow.checklogin(); 
    // Log.d("Match=",guestnot); 
    // if(guestnot.equals("match")){ 
    //  
     //} 

     return adapter; 
    } 

    /** Invoked by the Android on "doInBackground" is executed */ 
    @Override 
    protected void onPostExecute(SimpleAdapter adapter) { 

     // Setting adapter for the listview 
     mListView.setAdapter(adapter); 

    // Toast.makeText(countrymain.this, "label is="+adapter.getCount() 
     //  , Toast.LENGTH_SHORT).show(); 


     for(int i=0;i<adapter.getCount();i++){ 
      HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i); 
      String imgUrl = (String) hm.get("flag_path"); 


      ImageLoaderTask imageLoaderTask = new ImageLoaderTask(); 

      HashMap<String, Object> hmDownload = new HashMap<String, Object>(); 
      hm.put("flag_path",imgUrl); 
      hm.put("position", i); 

      // Starting ImageLoaderTask to download and populate image in the listview 
      imageLoaderTask.execute(hm); 
     } 
    }  
} 

/** AsyncTask to download and load an image in ListView */ 
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ 

    @Override 
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { 

     InputStream iStream=null; 
     String imgUrl = (String) hm[0].get("flag_path"); 
     int position = (Integer) hm[0].get("position"); 

     URL url; 
     try { 
      url = new URL(imgUrl); 

      // Creating an http connection to communicate with url 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

      // Connecting to url     
      urlConnection.connect(); 

      // Reading data from url 
      iStream = urlConnection.getInputStream(); 

      // Getting Caching directory 
      File cacheDirectory = getBaseContext().getCacheDir(); 

      // Temporary file to store the downloaded image 
      File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".jpg");    

      // The FileOutputStream to the temporary file 
      FileOutputStream fOutStream = new FileOutputStream(tmpFile); 

      // Creating a bitmap from the downloaded inputstream 
      Bitmap b = BitmapFactory.decodeStream(iStream);    

      // Writing the bitmap to the temporary file as png file 
      b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);    

      // Flush the FileOutputStream 
      fOutStream.flush(); 

      //Close the FileOutputStream 
      fOutStream.close();    

      // Create a hashmap object to store image path and its position in the listview 
      HashMap<String, Object> hmBitmap = new HashMap<String, Object>(); 

      // Storing the path to the temporary image file 
      hmBitmap.put("flag",tmpFile.getPath()); 

      // Storing the position of the image in the listview 
      hmBitmap.put("position",position);    

      // Returning the HashMap object containing the image path and position 
      return hmBitmap;     


     }catch (Exception e) {    
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(HashMap<String, Object> result) { 
     // Getting the path to the downloaded image 
     String path = (String) result.get("flag");   

     // Getting the position of the downloaded image 
     int position = (Integer) result.get("position"); 

     // Getting adapter of the listview 
     SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter(); 

     // Getting the hashmap object at the specified position of the listview 
     HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position); 

     // Overwriting the existing path in the adapter 
     hm.put("flag",path); 

     // Noticing listview about the dataset changes 
     adapter.notifyDataSetChanged(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater menuInflater = getMenuInflater(); 
    //menuInflater.inflate(R.layout.menu, menu); 

    menuInflater.inflate(R.menu.activity_main_actions, menu); 

    return true; 

} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    switch (item.getItemId()) { 
     // action with ID action_refresh was selected 
     case R.id.action_setting1s: 
      Intent m= new Intent(getApplicationContext(),MainActivity.class); 
      startActivity(m); 
      break; 
     // action with ID action_settings was selected 
     case R.id.action_setting2s: 
      Intent j = new Intent(getApplicationContext(),DataListView.class); 
      startActivity(j); 
      break; 
     case R.id.action_setting3s: 
      // Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT) 
       // .show(); 
      Intent k = new Intent(getApplicationContext(),OrderHistory.class); 
       startActivity(k); 
       break; 
     case R.id.action_setting4s: 
      // Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT) 
       // .show(); 
      Intent intent = new Intent(getApplicationContext(),AndroidPHPConnectionDemo.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      startActivity(intent); 

     // moveTaskToBack(true); 
      // android.os.Process.killProcess(android.os.Process.myPid()); 
      //System.exit(0); 
       break; 
     default: 
      break; 
     } 

     return true; 


} } 
0
<?xml version="1.0" encoding="utf-8"?>// gridView.xml 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 

<GridView 
    android:layout_height="wrap_content" 
    android:id="@+id/gridView1" 
    android:layout_width="match_parent" 
    android:numColumns="2" 
    android:horizontalSpacing="10dp" 
    android:verticalSpacing="10dp"> 
</GridView> 

<?xml version="1.0" encoding="utf-8"?> // grid_view_item.xml 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:gravity="center" 
    android:paddingTop="10dp" 
    android:paddingBottom="10dp"> 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/button01" /> 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="TextView" /> 

3

Для такого рода требование лучше использовать 'RecyclerView', вместо ListView и GridView, в recylerview один вариант, как 'recyclerview.setLayoutManager(layoutmanager)'.

LayoutManager для ListView:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); 

LayoutManager для GridView:

GridLayoutManager layoutManager = new GridLayoutManager(getActivity(),nColumns); 

для получения более подробной информации обратитесь к http://www.intertech.com/Blog/android-v5-lollipop-recyclerview-tutorial/

0

Один атрибут должен быть добавлен для получения GridView, кроме замены ListView с GridView.

То есть,

android:numColumns="auto_fit" 

также заменить ListView с GridView в файле Java.

+0

да и как я могу конвертировать список в gridview? – user1042911

+0

Просмотрите отредактированный ответ. – activesince93

0

Я изменил строку с Адаптер SimpleAdapter = новый простой адаптер (getBaseContext(), страны, R.layout.lv_layout, from, to);

к

SimpleAdapter адаптер = новый SimpleAdapter (getBaseContext(), страны, R.layout.grid_view_item, новый String [] { "флаг", "foodname", "fooddesc1", "foodprice"}, новый int [] {R.id.imageView1, R.id.textView1, R.id.textView2, R.id.textView3});

и работает нормально сейчас. большое спасибо!

Смежные вопросы