2014-12-16 4 views
5

Моя активность:Как получить динамический вид сетки?

package com.app.redbuslayout; 

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONObject; 



import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.ViewGroup.LayoutParams; 
import android.widget.ArrayAdapter; 
import android.widget.GridView; 
import android.widget.RelativeLayout; 
import android.widget.Toast; 

public class MainActivity extends Activity { 
    GridView grid; 
    RelativeLayout r1; 
    String maxrows; 
    int maxcol; 
    int[] imageId = { 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat ,R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 
       R.drawable.seat, 

       R.drawable.seat, 
       }; 

       @Override 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

      CustomGrid adapter = new CustomGrid(MainActivity.this, imageId); 
     RelativeLayout relativeLayout = new RelativeLayout(this); 

     // define the RelativeLayout layout parameters. 
     RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.FILL_PARENT, 
       RelativeLayout.LayoutParams.FILL_PARENT); 

     grid =new GridView(MainActivity.this); 

     grid.setLayoutParams(new GridView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
     grid.setNumColumns(maxcol); 



     grid.setAdapter(adapter); 
     relativeLayout.addView(grid); 

      // set the RelativeLayout as our content view 
      setContentView(relativeLayout, relativeLayoutParams); 

     new GetRoute().execute("http://sb2.reloadit.in/TravelServices.asmx/Getlayout"); 
    } 

    private  class GetRoute extends AsyncTask<String, Void, JSONObject> { 
      /*String mJourneyDate; 
      public GetData(String pJourneyDate) { 
       this.mJourneyDate = pJourneyDate; 
      }*/ProgressDialog pd = null; 
       @Override 
       protected void onPreExecute() { 
        super.onPreExecute(); 

        pd = ProgressDialog.show(MainActivity.this, "", "Loading...", true); 
       } 

       @Override 
       protected JSONObject doInBackground(String... params) { 
        String response; 

        try { 
         HttpClient httpclient = new DefaultHttpClient(); 
         HttpPost httppost = new HttpPost(params[0]); 
         List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2); 
         nameValuePair.add(new BasicNameValuePair("RouteScheduleID","428205707")); 

         nameValuePair.add(new BasicNameValuePair("JourneyDate","2014-12-16")); 


         httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
         HttpResponse responce = httpclient.execute(httppost); 

         HttpEntity httpEntity = responce.getEntity(); 

         response = EntityUtils.toString(httpEntity); 
         Log.d("response is", response); 

         return new JSONObject(response); 

        } catch (Exception ex) { 

         ex.printStackTrace(); 

        } 

        return null; 
       } 

       @Override 
       protected void onPostExecute(JSONObject result) 
       { 
        super.onPostExecute(result); 
        //Log.v("TAG_RESULTadapter",""+result); 

        pd.dismiss(); 
        if(result != null) 
        { 
         try 
         { 
          JSONObject jobj = result.getJSONObject("Response"); 
          String message = jobj.getString("Message"); 
          String issuceess = jobj.getString("IsSuccess"); 

          if(issuceess.equals("true")) 
          { 

           JSONObject layout = result.getJSONObject("Layout"); 
           // Log.v("TAG_routearray",""+layoutarray); 
            maxrows=layout.getString("MaxRows"); 
            maxcol=layout.getInt("MaxColumns"); 
           /* Log.v("TAG_maxrows",""+maxrows); 
            Log.v("TAG_Maxcol",""+maxcol);*/ 
            JSONArray routearray = layout.getJSONArray("SeatDetails"); 
            for (int i = 0; i < routearray.length(); i++) { 

            String Row = routearray.getJSONObject(i).getString("Row"); 
           // Log.v("TAG_routearray",""+Row); 
            String Col = routearray.getJSONObject(i).getString("Col"); 
            String Height = routearray.getJSONObject(i).getString("Height"); 
            String Width = routearray.getJSONObject(i).getString("Width"); 
            String SeatNo = routearray.getJSONObject(i).getString("SeatNo"); 
            String Gender = routearray.getJSONObject(i).getString("Gender"); 

             String Deck = routearray.getJSONObject(i).getString("Deck"); 
             String IsAvailable = routearray.getJSONObject(i).getString("IsAvailable"); 
             String Fare = routearray.getJSONObject(i).getString("Fare"); 
            Log.v("TAG_Maxfare",""+Fare); 

            } 

          } 
         } 


         catch (Exception e) 
         { 
          e.printStackTrace(); 
         } 
        } 
        else 
        { 
         Toast.makeText(MainActivity.this, "Network Problem", Toast.LENGTH_LONG).show(); 
        } 
       } 
} 
} 

класс Adapter:

  package com.app.redbuslayout; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class CustomGrid extends BaseAdapter{ 
    private Context mContext; 

    private final int[] Imageid; 
     public CustomGrid(Context c,int[] Imageid) { 
      mContext = c; 
      this.Imageid = Imageid; 

     } 
    @Override 
    public int getCount() { 
     // TODO Auto-generated method stub 
     return Imageid.length; 
    } 
    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
    @Override 
    public long getItemId(int position) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 
    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // TODO Auto-generated method stub 
     View grid; 
     LayoutInflater inflater = (LayoutInflater) mContext 
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      if (convertView == null) { 
      grid = new View(mContext); 
     grid = inflater.inflate(R.layout.row_grid, null); 

      ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image); 

      imageView.setImageResource(Imageid[position]); 
      } else { 
      grid = (View) convertView; 
      } 



     return grid; 
    } 
} 

В моем приложении с JSON я maxrows и maxcolumns. Основываясь на maxrow и maxcolumn, я хочу создать сетку с таким же количеством столбцов и строк. Каждая сетка содержит одно и то же изображение.

Как я могу создать это gridview динамически?

ответ

1
LazyAdapter adapter; 

adapter = new LazyAdapter(this, Col , Height , Width, SeatNo); 
     grid.setAdapter((ListAdapter) adapter); 

и LazyAdapter продолжается с BaseAdapter класса

public LazyAdapter(Activity a, String[] d, String[] textname, 
      String catID, String subCatIDD) { 
     activity = a; 
     data = d; 
     textdataamag = textname; 
     this.catID = catID; 
     this.subCatIDD = subCatIDD; 
     inflater = (LayoutInflater) activity 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    } 

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

public View getView(int position, View convertView, ViewGroup parent) { 
//here you get handle your view 

ex.

View vi = convertView; 
     if (convertView == null) 
      vi = inflater.inflate(R.layout.masterindex, null); 

     TextView text = (TextView) vi.findViewById(R.id.channelTXT); 
     ImageView image = (ImageView) vi.findViewById(R.id.channelIMG); 

     } 

return view 

обрабатывать LazyAdapter класс вы можете взять полную ссылку с http://www.javacodegeeks.com/2013/08/android-custom-grid-view-example-with-image-and-text.html класса CustomGridViewAdapter.java

+0

спасибо за ваш ответ. Но это не работает. Я хочу установить строки и столбцы динамически на основе данных json. Изображение в каждой строке и столбце одинаково –

+0

что такое проблема? –

+0

Я отредактировал мой код suman. теперь скажите мне, как я установил maxcols в setNumColumn() –

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