java - 如何将可绘制图像放入 gridview 中?

标签 java android xml gridview fragment

我有一个包含 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 代码,我制作了 ListView 。该 ListView 填充了一个字符串数组。

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

最佳答案

您必须使用自定义适配器将图像放入 gridview

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(放入资源文件夹中)

{ "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"
  }
] }

希望这会起作用..

关于java - 如何将可绘制图像放入 gridview 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29235322/

相关文章:

java - 关于 Nexus 工件和构建说明的 Dockerfile 最佳实践

java - android外部jar问题

java - Adobe Omniture For Android在trackAction上失败

java - XML - Java 中的 XPath DOM 解析器

php - 在递归函数中获取 xml 节点的 xpath

java - 数据绑定(bind)不是将数据与android中的xml绑定(bind)

java - 验证 boolean 值 true

java - 如何在java中并行迭代集合?

java - 大家好,请问一下按下按钮时的声音处理吗?

xml - XPath,两个用“和”选择条件?