【问题标题】:How can I put drawable image into gridview?如何将可绘制图像放入gridview?
【发布时间】:2015-03-24 14:32:55
【问题描述】:

我有一个 5 列的 gridview,如何在第 4 列和第 5 列中添加我在可绘制文件夹中的图像?问题是作为一个字符串数组列表不能让我抓到可绘制,因为它是一个整数。

这是我的 XML:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/scrolView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical">


    <GridView
        android:id="@+id/Grid"
        android:numColumns="5"
        android:stretchMode="columnWidth"
        android:layout_width="match_parent"
        android:gravity="center"
        android:columnWidth="120dp"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:layout_height="2000dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="30dp"></GridView>


</LinearLayout>

这是我调用 carrito.xml 的 java 代码,我创建了列表视图。这个列表视图填充了一个字符串数组。

public class carrito extends Fragment {

protected Context context;
private int numComandesCarrito;
private String[][] CarritoProductes;

private double Total;
DecimalFormat precision = new DecimalFormat("0.00");

NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(Total);

public carrito(){

}
public void setContext (Context context){
    this.context = context;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {



   int i, i2;

    numComandesCarrito = ((MainActivity) context).getNumComandesCarrito();
   // Toast.makeText(context, Integer.toString(numComandesCarrito), Toast.LENGTH_LONG).show();
    CarritoProductes = ((MainActivity) context).getCarritoProductes();
    Total = 0;

    ArrayList<String> lineasPedido = new ArrayList<String>();
    ArrayList<Integer> itemsimg = new ArrayList( );



    //Afegim la capçalera de la grid
    lineasPedido.add("Plat");
    lineasPedido.add("Quantitat");
    lineasPedido.add("Preu");

    for (i= 0; i < numComandesCarrito; i++){
        for (i2 = 0; i2<3; i2++){
            if (i2 == 2) {
                lineasPedido.add(precision.format(Double.parseDouble(CarritoProductes[i2][i])) + " €");
                Total = Total + Double.parseDouble(CarritoProductes[i2][i]);
            }
            else{
                lineasPedido.add(CarritoProductes[i2][i]);
            }
        }
        itemsimg.add(R.drawable.botonmenos);

}

    lineasPedido.add("");
    lineasPedido.add("");
    lineasPedido.add("Total: " + (precision.format(Total)) + " €");


    View rootView = inflater.inflate(R.layout.carrito, container, false);
    GridView grdView = (GridView)rootView.findViewById(R.id.grdComanda);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, lineasPedido);

    grdView.setAdapter(adapter);





    return rootView;
}

【问题讨论】:

    标签: java android xml gridview fragment


    【解决方案1】:

    您必须使用自定义适配器将图像放入网格视图中

    activity.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:horizontalSpacing="5dp"
        android:numColumns="2"
        android:verticalSpacing="5dp" >
    </GridView>
    
    </RelativeLayout>
    

    行.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layoutbg"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="250dp"
        android:gravity="center"
        android:orientation="horizontal" >
    
        <ImageView
            android:id="@+id/img"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_alignParentBottom="true"
            android:gravity="center"
            android:orientation="horizontal" >
    
            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:paddingLeft="15dp"
                android:text="TextView" />
    
            <TextView
                android:id="@+id/num"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="right"
                android:paddingRight="15dp"
                android:text="TextView" />
        </LinearLayout>
    </RelativeLayout>
    </RelativeLayout>
    

    FriendAdapter.java

    public class FriendAdapter extends ArrayAdapter<FriendBean>{
    private Context mCtx;
    private ArrayList<FriendBean> items = new ArrayList<FriendBean>();
    private ViewHolder mHolder;
    ImageLoader imgLoader = new ImageLoader(mCtx);
    public LayoutInflater inflater;
    int loader = R.drawable.loader;
    
    public FriendAdapter(Context context,  int textViewResourceId,  ArrayList<FriendBean> items) {
        super(context,  textViewResourceId, items);
        this.items = items;
        this.mCtx = context;
    
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
    
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v=vi.inflate(R.layout.row, null);
                mHolder=new ViewHolder();
                mHolder.mImage=(ImageView)v.findViewById(R.id.img);
                mHolder.mName=(TextView)v.findViewById(R.id.name);
                mHolder.mPh=(TextView)v.findViewById(R.id.num);
                mHolder.mlayoutbg=(RelativeLayout)v.findViewById(R.id.layoutbg);
                v.setTag(mHolder);
            }
        else{
            mHolder=(ViewHolder)v.getTag();
        }
        imgLoader.DisplayImage(items.get(position).getImage(), loader, mHolder.mImage);
          //mHolder.mImage.setBackgroundResource(items.get(position).getImage());
        mHolder.mName.setText(items.get(position).getName());
        mHolder.mPh.setText(items.get(position).getPh());
        mHolder.mlayoutbg.setBackgroundColor(Color.GREEN);
        //      if(position%3==1){
        //          mHolder.mlayoutbg.setBackgroundColor(Color.GRAY);
        //      }else if(position%3==2){
        //          mHolder.mlayoutbg.setBackgroundColor(Color.WHITE);
        //      }else{
        //          mHolder.mlayoutbg.setBackgroundColor(Color.YELLOW);
        //      }
            return v;
    }
    
    public class ViewHolder {
        public  ImageView mImage;
        public TextView mName;
        public TextView mPh;
        public RelativeLayout mlayoutbg;
    
    }
    
    }
    

    FriendBean.java

    package com.example.bean;
    
    public class FriendBean {
    private String Image;
    private String name;
    private String ph;
    private String des;
    
    public FriendBean(String Image, String name, String ph, String des) {
        this.Image = Image;
        this.name = name;
        this.ph = ph;
        this.des = des;
    
    }
    
    public String getImage() {
        return Image;
    }
    
    public void setImage(String image) {
        Image = image;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getPh() {
        return ph;
    }
    
    public void setPh(String ph) {
        this.ph = ph;
    }
    
    public String getDes() {
        return des;
    }
    
    public void setDes(String des) {
        this.des = des;
    }
    }
    

    MainActivity.java

    public class MainActivity extends Activity {
    
    private GridView mList;
    private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
    private FriendAdapter friendAdapter;
    String friend_name, friend_phone, url, des;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mList = (GridView) findViewById(R.id.gridView1);
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
    
        try {
            br = new BufferedReader(new InputStreamReader(getAssets().open(
                    "gridarray.json")));
            String temp;
            while ((temp = br.readLine()) != null)
                sb.append(temp);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } finally {
            try {
                br.close(); // stop reading
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String myjsonstring = sb.toString();
    
        try {
            JSONObject obj = new JSONObject(myjsonstring);
            JSONArray jsonarray = obj.getJSONArray("json");
            Log.e("Length", "" + jsonarray.length());
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject jsonObj = jsonarray.getJSONObject(i);
                friend_name = jsonObj.getString("friend_name");
                friend_phone = jsonObj.getString("friend_phone");
                url = jsonObj.getString("image_url");
                des = jsonObj.getString("des");
                FriendBean bean = new FriendBean(url, friend_name, friend_phone,
                        des);
                arr.add(bean);
                Log.e("u", url);
                Log.e("friend_name", friend_name);
                Log.e("friend_phone", friend_phone);
            }
    
            friendAdapter = new FriendAdapter(MainActivity.this, R.layout.row, arr);
            mList.setAdapter(friendAdapter);
            mList.setOnItemClickListener(new OnItemClickListener() {
    
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), "Clicked on " + arg2,
                            Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(getApplicationContext(), NewPage.class);
                    i.putExtra("friend_name", arr.get(arg2).getName());
                    i.putExtra("friend_phone", arr.get(arg2).getPh());
                    i.putExtra("url", arr.get(arg2).getImage());
                    i.putExtra("des", arr.get(arg2).getDes());
                    startActivity(i);
                }
            });
    
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    gridarray.json (放到asset文件夹)

    { "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
        "friend_name" : "Madhumoy",
        "friend_phone" : "123",
        "des" : "Hi I'm Madhumoy"
      },
      { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
        "friend_name" : "Sattik",
        "friend_phone" : "123",
        "des" : "Hi I'm Sattik"
      },
      { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
        "friend_name" : "Koushik",
        "friend_phone" : "123",
        "des" : "Hi I'm Koushik"
      },
      { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
        "friend_name" : "Himanshu",
        "friend_phone" : "123",
        "des" : "Hi I'm Himanshu"
      },
      { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
        "friend_name" : "Sandy",
        "friend_phone" : "123",
        "des" : "Hi I'm Sandy"
      }
    ] }
    

    希望这会奏效..

    【讨论】:

      【解决方案2】:

      也许可以试试这样的东西?用户 cmets 在大多数情况下似乎是积极的。 http://www.compiletimeerror.com/2013/02/display-images-in-gridview.html#.VRF2I2NTf5w

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多