1
public class MainActivity extends Activity {

GridView gridView;
LazyAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    gridView = (GridView) findViewById(R.id.grid_view);
    adapter=new LazyAdapter(this, mStrings);
    gridView.setAdapter(adapter);

    Button b=(Button)findViewById(R.id.button2);
    b.setOnClickListener(listener);
}

@Override
public void onDestroy()
{
    adapter.imageLoader.stopThread();
    gridView.setAdapter(null);
    super.onDestroy();
}


public OnClickListener listener=new OnClickListener(){
    public void onClick(View arg0) {
        adapter.imageLoader.clearCache();
        adapter.notifyDataSetChanged();
    }
};



private String[] mStrings={
        "http://www.globaltvbc.com/uploadedImages/Global_News/Content/Wallpaper.jpeg",
        "http://cdn.windows7themes.net/themes/halo-3-hd-wallpaper.jpg",
   };
}

问题是我想在gridview上显示项目并全屏显示项目。我想包含任何代码以全屏显示gridview项目与MainActivity在同一类中。我不希望我的代码是在一个新的班级。

4

2 回答 2

1

我给你我的代码根据你的需要编辑这个|主要活动

package com.mypack;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;

public class GridViewActivity extends Activity implements OnItemClickListener {



    List<RowItem4> rowItems;

    private GridView gridView;

    private Button galleryButton;

    private Button shareButton;
    private String[] mStringArray;
    public static final Integer[] partyid = { 1, 2, 3, 4, 18, 19, 20 };
    int i = 1;
    private String xml;
    String output = "";

    /*private static final String NAMESPACE = "";
    private static final String URL = "";
    private static final String SOAP_ACTION = "";
    private static final String METHOD_NAME = "";*/


    private int pos;
    private ProgressDialog progressDialog;
    private int galleryId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.grid_view);

        Intent i = getIntent();
        pos = i.getIntExtra("position", 0);
        galleryId = i.getIntExtra("galleryId", 0);

        progressDialog = ProgressDialog.show(GridViewActivity.this, "",
                "Loading...");
        Thread myThread = new Thread() {

            private GridViewAdapter adapter;

            public void run() {
                getImages();

                rowItems = new ArrayList<RowItem4>();
                for (int i = 0; i < mStringArray.length; i++) {
                    RowItem4 item = new RowItem4(mStringArray[i]);
                    rowItems.add(item);
                }
                // LoadImageFromURL(""
                // + output);
                adapter = new GridViewAdapter(GridViewActivity.this, rowItems);

                runOnUiThread(new Runnable() {
                    public void run() {

                        try {

                            gridView.setAdapter(adapter);
                            gridView.setOnItemClickListener(GridViewActivity.this);

                            progressDialog.dismiss();
                        } catch (final Exception ex) {
                            Log.i("---", "Exception in thread");
                        }
                    }
                });

            }
        };
        myThread.start();

        setUpView();

    }

    private void getImages() {
        final String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" "
                + "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
                + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
                + "xmlns:tns=\"urn:registerwsdl\">" + "<SOAP-ENV:Body>"
                + "<tns:register " + "xmlns:tns=\"urn:registerwsdl\">"
                + "<galleryid xsi:type=\"xsd:integer\">" + galleryId
                + "</galleryid>" + "<partyid xsi:type=\"xsd:integer\">"
                + partyid[pos] + "</partyid>" + "</tns:register>" +

                // "</SOAP-ENV:Body></SOAP-ENV:Envelope>",Name,Email,Password,Status,Type,Date];
                "</SOAP-ENV:Body></SOAP-ENV:Envelope>";

        System.out.println("------------" + envelope);

        CallWebService(URL, SOAP_ACTION, envelope);

        org.w3c.dom.Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            ArrayList<String> myList = new ArrayList<String>();
            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);

            NodeList nl1 = doc.getElementsByTagName("response");
            for (int j = 0; j < nl1.getLength(); j++) {

                NodeList nl = doc.getElementsByTagName("url");

                for (int i = 0; i < nl.getLength(); i++) {

                    Node node = nl.item(i);

                    myList.add(node.getFirstChild().getNodeValue());

                }
            }
            mStringArray = new String[myList.size()];
            mStringArray = myList.toArray(mStringArray);

            for (int i = 0; i < mStringArray.length; i++) {
                Log.d("string is", (mStringArray[i]));
            }

        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

    }

    String CallWebService(String url, String soapAction, String envelope) {
        final DefaultHttpClient httpClient = new DefaultHttpClient();
        // request parameters

        HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 20000);
        HttpConnectionParams.setSoTimeout(params, 25000);
        // set parameter
        HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

        // POST the envelope
        HttpPost httppost = new HttpPost(url);
        // add headers
        httppost.setHeader("soapaction", soapAction);
        httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

        String responseString = "";
        try {

            // the entity holds the request
            HttpEntity entity = new StringEntity(envelope);
            httppost.setEntity(entity);

            // Response handler

            ResponseHandler<String> rh = new ResponseHandler<String>() {
                // invoked when client receives response

                public String handleResponse(HttpResponse response)
                        throws ClientProtocolException, IOException {

                    // get response entity
                    HttpEntity entity = response.getEntity();

                    // read the response as byte array
                    StringBuffer out = new StringBuffer();
                    byte[] b = EntityUtils.toByteArray(entity);

                    // write the response byte array to a string buffer
                    out.append(new String(b, 0, b.length));

                    return out.toString();
                }
            };

            responseString = httpClient.execute(httppost, rh);

        } catch (Exception e) {
            Log.v("exception", e.toString());
        }

        xml = responseString.toString();
        // close the connection
        System.out.println("xml file ------" + xml);
        httpClient.getConnectionManager().shutdown();
        return responseString;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (i == 2) {

            if (galleryButton.getVisibility() == View.VISIBLE) {
                galleryButton.setVisibility(View.INVISIBLE);

                shareButton.setVisibility(View.INVISIBLE);

            } else {
                galleryButton.setVisibility(View.VISIBLE);

                shareButton.setVisibility(View.VISIBLE);

            }

            i = 0;
        }
        i++;
        super.dispatchTouchEvent(ev);
        return false;

    }

    /*
     * public OnTouchListener touch = new View.OnTouchListener() {
     * 
     * public boolean onTouch(View v, MotionEvent event) {
     * //System.out.println("onTouch       =============-----------"); if
     * (galleryButton.getVisibility() == v.VISIBLE) {
     * galleryButton.setVisibility(v.INVISIBLE);
     * 
     * shareButton.setVisibility(v.INVISIBLE);
     * 
     * } else { galleryButton.setVisibility(v.VISIBLE);
     * 
     * shareButton.setVisibility(v.VISIBLE);
     * 
     * } return false; } };
     */
    private void setUpView() {

        gridView = (GridView) findViewById(R.id.gridView1);

        galleryButton = (Button) findViewById(R.id.gallery_button);

        shareButton = (Button) findViewById(R.id.share_button);

        // relativeLayout1.setOnTouchListener(touch);

    }

    public void onItemClick(AdapterView<?> adapterView, View view,
            int position, long id) {

        Intent i = new Intent(getApplicationContext(), ShowImageActivity.class);
        i.putExtra("image", mStringArray[position]);
        i.putExtra("galleryId", galleryId);
        startActivity(i);

    }

}

RowItem4 对象类

package com.mypack;

public class RowItem4 {
    private String imageId;

    public String getImageId() {
        return imageId;
    }

    public void setImageId(String imageId) {
        this.imageId = imageId;
    }

    public RowItem4(String mStringArray) {
        this.imageId = mStringArray;

    }

}

GridViewAdapter 扩展 BaseAdapter

package com.mypack;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;





import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class GridViewAdapter extends BaseAdapter {



    Context context;
    List<RowItem4> rowItems;
    private ViewHolder holder;
    private Drawable d;

    public GridViewAdapter(Context context, List<RowItem4> rowItems) {
        super();
        this.context = context;
        this.rowItems = rowItems;
    }

    private class ViewHolder {
        ImageView imageView;
        public int position;


    }

    public int getCount() {
        // TODO Auto-generated method stub
        return rowItems.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return rowItems.get(position);
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return rowItems.indexOf(getItem(position));
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        holder = null;

        LayoutInflater mInflater = (LayoutInflater)
            context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.grid_image_view, null);
            holder = new ViewHolder();


            holder.imageView = (ImageView) convertView.findViewById(R.id.grid_item_image);

            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        RowItem4 rowItem = (RowItem4) getItem(position);

        holder.position = position;
        GetXMLTask task = new GetXMLTask(position,holder);

        task.execute(new String[] { ""+rowItem.getImageId() });


        //holder.imageView.setImageDrawable(d);
        return convertView;
    }

    /*private Drawable LoadImageFromURL(String url)
    {
    try
    {
    InputStream is = (InputStream) new URL(url).getContent();
    d = Drawable.createFromStream(is, "src");
    return d;
    }catch (Exception e) {
    System.out.println(e);
    return null;
    }
    }*/


    private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
        private int mPosition;
        private ViewHolder mHolder;
        public GetXMLTask(int position, ViewHolder holder) {
            mPosition = position;
            mHolder = holder;
        }

        protected Bitmap doInBackground(String... urls) {
            Bitmap map = null;
            for (String url : urls) {
                map = downloadImage(url);
            }
            return map;
        }

        // Sets the Bitmap returned by doInBackground
        protected void onPostExecute(Bitmap result) {
            if (mHolder.position == mPosition)
            {
            mHolder.imageView.setImageBitmap(result);
        }
        }

        // Creates Bitmap from InputStream and returns it
        private Bitmap downloadImage(String url) {
            Bitmap bitmap = null;
            InputStream stream = null;
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inSampleSize = 1;

            try {
                stream = getHttpConnection(url);
                bitmap = BitmapFactory.
                        decodeStream(stream, null, bmOptions);
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return bitmap;
        }

        // Makes HttpURLConnection and returns InputStream
        private InputStream getHttpConnection(String urlString)
                throws IOException {
            InputStream stream = null;
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();

            try {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return stream;
        }
    }
}

这段代码是如果你想在第二个活动上加载图像,如果你想在同一个活动上加载图像,只需在主活动中添加用于添加弹出窗口的代码。我想现在很清楚

于 2012-11-26T04:15:54.187 回答
1

如果你想在同一个活动上加载全屏,那么你应该使用弹出窗口来显示图像。

或者最好的解决方案是在您的主要活动上实施 onItemClickListener 并单击按位置获取项目并将图像 url 传递给下一个活动以将其加载到那里。

于 2012-11-24T07:34:38.880 回答