如何在网格视图android中的每一行和每列使用相同的图像?

时间:2014-12-17 08:57:15

标签: android

如何在网格视图中为每个行和列使用相同的图像。在我的服务应用程序中,我得到了maxcol和maxrow。基于我想要创建具有相同图像的网格视图的条件。如果maxcol 5和maxrow 14,现在我想创建具有相同图像的网格视图14x5。请帮帮我。

主要活动:

 public class MainActivity extends Activity {
    GridView grid;
    RelativeLayout r1;
    int maxrows, maxcol;
    ArrayList<LayoutData> data = new ArrayList<LayoutData>();
     ArrayList<HashMap<String, String>> sheetdetails = new ArrayList<HashMap<String, String>>();

              @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        grid=(GridView)findViewById(R.id.gridview);

        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","430723410"));

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


                         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.getInt("MaxRows");

                                  maxcol=layout.getInt("MaxColumns");
                                  grid.setNumColumns(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");
                                       LayoutData ld= new LayoutData();
                                        ld.setRow(Row);
                                        ld.setCol(Col);
                                        ld.setHeight(Height);
                                        ld.setWidth(Width);
                                        ld.setSeatno(SeatNo);
                                        ld.setGender(Gender);
                                        ld.setDeck(Deck);
                                        ld.setIsavailable(IsAvailable);
                                        ld.setFare(Fare);
                                        data.add(ld);



                                     Log.v("TAG_Maxfare",""+Fare);
                                     HashMap<String, String> map = new HashMap<String, String>();
                                     map.put("Row", Row);
                                     map.put("Col", Col);
                                     map.put("Height", Height);
                                     map.put("Width", Width);
                                     map.put("SeatNo", SeatNo);
                                     map.put("Deck", Deck);
                                     map.put("IsAvailable", IsAvailable);
                                     if(SeatNo.equalsIgnoreCase("")){
                                         map.put("seat_img", ""+R.drawable.noseat);
                                        }
                                     else{
                                          if(IsAvailable.equalsIgnoreCase("false")){
                                              map.put("seat_img", ""+R.drawable.seatgreen);
                                          }
                                         /* if(IsAvailable.equalsIgnoreCase("false")){
                                              map.put("seat_img", ""+R.drawable.seatgreen);
                                          }*/else if(IsAvailable.equalsIgnoreCase("true")){
                                              map.put("seat_img", ""+R.drawable.seat);
                                          }
                                        }
                                     map.put("Fare", Fare);
                                     sheetdetails.add(map);

                                    }
                                    CustomGrid adapter = new CustomGrid(MainActivity.this, sheetdetails);
                                    grid.setAdapter(adapter);

                            }
                        }


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

ADAPTER CLASS:

![import java.util.ArrayList;
import java.util.HashMap;

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;
    ArrayList<HashMap<String, String>> sheetdetails = new ArrayList<HashMap<String, String>>();
     public CustomGrid(Context c,ArrayList<HashMap<String, String>> sheetdetails) {
         mContext = c;
         this.sheetdetails= sheetdetails;
    }@Override
     public int getCount() {
         // TODO Auto-generated method stub
         return sheetdetails.size();
     }@Override
     public Object getItem(int position) {
         // TODO Auto-generated method stub
         return sheetdetails.get(position);
     }
    @Override
    public long getItemId(int arg0) {
        // 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);

            HashMap<String, String> map = sheetdetails.get(position);
            imageView.setImageResource(Integer.valueOf(map.get("seat_img")));


        } else {
            grid = (View) convertView;
        }

        return grid;
    }
  }][1]

JSON:

 {
    "ExtensionData": {},
    "Response": {
        "ExtensionData": {},
        "Message": "",
        "IsSuccess": true
    },
    "Route": {
        "ExtensionData": {},
        "RouteScheduleId": 428205707,
        "JourneyDate": "/Date(1418668200000)/",
        "CompanyId": 3964,
        "CompanyName": "KPN Travels",
        "FromCityId": 2667,
        "FromCityName": "hyderabad",
        "ToCityId": 2445,
        "ToCityName": "bangalore",
        "DepartureTime": "/Date(1418716800000)/",
        "DepTime": "2014-12-16T13:30:00",
        "ArrivalTime": "/Date(1418752800000)/",
        "ArrTime": "2014-12-16T23:30:00",
        "Fare": 1000,
        "SeaterFareNAC": 0,
        "SeaterFareAC": 1000,
        "SleeperFareNAC": 0,
        "SleeperFareAC": 0,
        "HasAC": true,
        "HasNAC": false,
        "HasSeater": true,
        "HasSleeper": false,
        "BusLabel": "MULTI AXLE",
        "RouteRemarks": null,
        "BusTypeName": "2+2 (MULTI AXLE) : 44",
        "CommPCT": 0,
        "CommAmount": 90
    },
    "Layout": {
        "ExtensionData": {},
        "MaxRows": 14,
        "MaxColumns": 5,
        "SeatDetails": [
            {
                "ExtensionData": {},
                "Row": 0,
                "Col": 2,
                "Height": 1,
                "Width": 1,
                "SeatNo": "",
                "Gender": "M",
                "IsAisle": true,
                "Deck": 1,
                "IsAC": true,
                "IsSleeper": false,
                "IsAvailable": false,
                "Fare": 0,
                "ChildFare": 0,
                "InfantFare": 0
            },

2 个答案:

答案 0 :(得分:1)

将您的JSON值存储在数组列表中。将ArrayList传递给CustomGrid.class

 ArrayList<HashMap<String, String>> sheetdetails = new ArrayList<HashMap<String, String>>();
 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);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("Row", Row);
        map.put("Col", Col);
        map.put("Height", Height);
        map.put("Width", Width);
        map.put("SeatNo", SeatNo);
        map.put("Deck", Deck);
        map.put("IsAvailable", IsAvailable);
        if(SeatNo.equalsIgnoreCase("")){
         map.put("seat_img", ""+R.drawable.blank_img);
        }else{
          if(IsAvailable.equalsIgnoreCase("Available")){
              map.put("seat_img", ""+R.drawable.avaliable_seat_img);
          }else if(IsAvailable.equalsIgnoreCase("Not Available")){
              map.put("seat_img", ""+R.drawable.not_avaliable_seat_img);
          }
        }
        map.put("Fare", Fare);
        sheetdetails.add(map);
 }

CustomGrid adapter = new CustomGrid(MainActivity.this, sheetdetails);
yourgridview.setAdapter(adapter);

<强> CustomGrid.Class

更改此

 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;
 }

 ArrayList<HashMap<String, String>> sheetdetails = new ArrayList<HashMap<String, String>>();
 public CustomGrid(Context c,ArrayList<HashMap<String, String>> sheetdetails) {
     mContext = c;
     this.sheetdetails= sheetdetails;
}@Override
 public int getCount() {
     // TODO Auto-generated method stub
     return sheetdetails.size();
 }@Override
 public Object getItem(int position) {
     // TODO Auto-generated method stub
     return list.get(position);
 }

在getview中

@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);

            HashMap<String, String> map = sheetdetails.get(position);
            imageView.setImageResource(Integer.valueOf(map.get("seat_img")));

        } else {
            grid = (View) convertView;
        }

        return grid;
    }

答案 1 :(得分:0)

如果你想要相同的图像,那么不要使用它:

imageView.setImageResource(Imageid[position]);

在您的getView方法中,只需设置一个图片资源:

imageView.setImageResource(R.drawable.ic_launcher); //replace id with your drawable id

如果要在GridView的所有项目中设置单个图像,则不需要维护可绘制数组。

修改

如果要将图像资源数组传递给BaseAdapter,则可以使用一个图像资源传递数组。像这样:

int[] Imageid = new int[]{R.drawable.myimage};

只需对所有项目使用Imageid [0]而不是Imageid [位置]。

imageView.setImageResource(Imageid[0]);

希望这有帮助。

修改

如果您想根据座位的可用性更改值,您可以使用2个图像的数组:

int[] Imageid = new int[]{R.drawable.available_seat, R.drawable.not_available_seat};

在您的getView方法中,只需检查您在json响应中获得的变量 IsAvailable 的可用性并相应地设置图像资源:

if(isAvailable)  //you will need to declare a boolean variable and set it to true or false based on IsAvailable's value
    imageView.setImageResource(Imageid[0]);
else
    imageView.setImageResource(Imageid[1]);

希望这可以解除你的怀疑。