【问题标题】:how do i implement an on click listener to fullscreen each image in this grid view?如何实现点击监听器以全屏显示此网格视图中的每个图像?
【发布时间】:2014-10-30 18:56:18
【问题描述】:

大家好,所以我从 instagram 解析了一个 json 数组,以在网格视图中显示用户库你

主要活动

public class MainActivity extends Activity {
private InstagramSession mInstagramSession;
private Instagram mInstagram;

private ProgressBar mLoadingPb;
private GridView mGridView;

private static final String CLIENT_ID = "83549f9eb76f4a5b90daf6e4e14da107";
private static final String CLIENT_SECRET = "6df26b0c8f664323a07126bfe8511651";
private static final String REDIRECT_URI = "http://www.yahoo.com";

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

    mInstagram          = new Instagram(this, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);

    mInstagramSession   = mInstagram.getSession();

    if (mInstagramSession.isActive()) {
        setContentView(R.layout.activity_user);

        InstagramUser instagramUser = mInstagramSession.getUser();

        mLoadingPb  = (ProgressBar) findViewById(R.id.pb_loading);
        mGridView   = (GridView) findViewById(R.id.gridView);

        ((TextView) findViewById(R.id.tv_name)).setText(instagramUser.fullName);
        ((TextView) findViewById(R.id.tv_username)).setText(instagramUser.username);

        ((Button) findViewById(R.id.btn_logout)).setOnClickListener(new View.OnClickListener() {                
            @Override
            public void onClick(View arg0) {
                mInstagramSession.reset();

                startActivity(new Intent(MainActivity.this, MainActivity.class));

                finish();
            }
        });

        ImageView userIv = (ImageView) findViewById(R.id.iv_user);

        DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_user)
                .showImageForEmptyUri(R.drawable.ic_user)
                .showImageOnFail(R.drawable.ic_user)
                .cacheInMemory(true)
                .cacheOnDisc(false)
                .considerExifParams(true)
                .build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)                                               
                .writeDebugLogs()
                .defaultDisplayImageOptions(displayOptions)             
                .build();

        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);

        AnimateFirstDisplayListener animate  = new AnimateFirstDisplayListener();

        imageLoader.displayImage(instagramUser.profilPicture, userIv, animate);

        new DownloadTask().execute();

    } else {
        setContentView(R.layout.activity_main);

        ((Button) findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {           
            @Override
            public void onClick(View arg0) {                    
                mInstagram.authorize(mAuthListener);    
            }
        });
    }
}

private void showToast(String text) {
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}

private Instagram.InstagramAuthListener mAuthListener = new Instagram.InstagramAuthListener() {         
    @Override
    public void onSuccess(InstagramUser user) {
        finish();

        startActivity(new Intent(MainActivity.this, MainActivity.class));
    }

    @Override
    public void onError(String error) {     
        showToast(error);
    }

    @Override
    public void onCancel() {
        showToast("OK. Maybe later?");

    }
};

public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

    static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        if (loadedImage != null) {
            ImageView imageView = (ImageView) view;
            boolean firstDisplay = !displayedImages.contains(imageUri);
            if (firstDisplay) {
                FadeInBitmapDisplayer.animate(imageView, 500);
                displayedImages.add(imageUri);
            }
        }
    }
}

public class DownloadTask extends AsyncTask<URL, Integer, Long> {
    ArrayList<String> photoList;

    protected void onCancelled() {

    }

    protected void onPreExecute() {

    }

    protected Long doInBackground(URL... urls) {         
        long result = 0;

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>(1);

            params.add(new BasicNameValuePair("count", "20"));

            InstagramRequest request = new InstagramRequest(mInstagramSession.getAccessToken());
            String response          = request.createRequest("GET", "/users/21846697/media/recent", params);

            if (!response.equals("")) {
                JSONObject jsonObj  = (JSONObject) new JSONTokener(response).nextValue();                   
                JSONArray jsonData  = jsonObj.getJSONArray("data");

                int length = jsonData.length();

                if (length > 0) {
                    photoList = new ArrayList<String>();

                    for (int i = 0; i < length; i++) {
                        JSONObject jsonPhoto = jsonData.getJSONObject(i).getJSONObject("images").getJSONObject("low_resolution");

                        photoList.add(jsonPhoto.getString("url"));
                    }
                }
            }
        } catch (Exception e) { 
            e.printStackTrace();
        }

        return result;
    }

    protected void onProgressUpdate(Integer... progress) {                  
    }

    protected void onPostExecute(Long result) {
        mLoadingPb.setVisibility(View.GONE);

        if (photoList == null) {
            Toast.makeText(getApplicationContext(), "No Photos Available", Toast.LENGTH_LONG).show();
        } else {
            DisplayMetrics dm = new DisplayMetrics();

            getWindowManager().getDefaultDisplay().getMetrics(dm);

            int width   = (int) Math.ceil((double) dm.widthPixels / 2);
            width=width-50;
            int height  = width;

            PhotoListAdapter adapter = new PhotoListAdapter(MainActivity.this);

            adapter.setData(photoList);
            adapter.setLayoutParam(width, height);

            gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    //code goes here to get the image url based on the position
                    Intent myintent=new Intent(currentActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", value);
                    startActivity(myintent);
                }
            });

            mGridView.setAdapter(adapter);
            }
        }                
    }
}

照片列表适配器

public class PhotoListAdapter extends BaseAdapter {
private Context mContext;

private ImageLoader mImageLoader;
private AnimateFirstDisplayListener mAnimator;

private ArrayList<String> mPhotoList;

private int mWidth;
private int mHeight;

public PhotoListAdapter(Context context) {
    mContext = context;

    DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.instagram_logo)
            .showImageForEmptyUri(R.drawable.instagram_logo)
            .showImageOnFail(R.drawable.instagram_logo)
            .cacheInMemory(true)
            .cacheOnDisc(false)
            .considerExifParams(true)
            .build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)                                            
            .writeDebugLogs()
            .defaultDisplayImageOptions(displayOptions)             
            .build();

    mImageLoader = ImageLoader.getInstance();
    mImageLoader.init(config);

    mAnimator  = new AnimateFirstDisplayListener();
}

public void setData(ArrayList<String> data) {
    mPhotoList = data;
}

public void setLayoutParam(int width, int height) {
    mWidth  = width;
    mHeight = height;
}

@Override
public int getCount() {
    return (mPhotoList == null) ? 0 : mPhotoList.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageIv;

    if (convertView == null) {
        imageIv = new ImageView(mContext);

        imageIv.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight));
        imageIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageIv.setPadding(0, 0, 0, 0); 
    } else {
        imageIv = (ImageView) convertView;
    }

    mImageLoader.displayImage(mPhotoList.get(position), imageIv, mAnimator);

    return imageIv;
    }
}

全屏图像视图

package net.londatiga.android.example;

public class FullscreenImageView {

String imageURL = getIntent().getStringExtra("SelectedImageURL");

}

Activity_user.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"    
android:padding="@dimen/activity_vertical_margin"
android:background="#000000">

<ImageView
    android:id="@+id/iv_user"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:contentDescription="@string/app_name"
    android:src="@drawable/ic_user" />

<LinearLayout
    android:layout_toRightOf="@+id/iv_user"
    android:layout_alignTop="@+id/iv_user"
    android:layout_alignBottom="@+id/iv_user"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="@dimen/activity_vertical_margin"        
    android:orientation="vertical"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:textColor="#fff"
        android:textStyle="bold"
        android:textSize="17sp"
        android:text="Name"/>

    <TextView
        android:id="@+id/tv_username"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:textColor="#fff"
        android:text="Username"/>

</LinearLayout>

<Button
    android:id="@+id/btn_logout"
    android:layout_below="@+id/iv_user"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:textSize="5pt"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:textColor="#ff0000"
    android:background="#000000"
    android:text="@string/text_signout" />

<RelativeLayout
    android:layout_below="@+id/btn_logout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"  >

     <GridView
        android:id="@+id/gridView"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="5dp"
        android:padding="5dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:id="@+id/pb_loading"             
        android:layout_width="100dp" 
        android:layout_height="100dp"       
        android:layout_centerInParent="true"/>




</RelativeLayout>

activity_fullscreen

<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"
android:orientation="vertical"
tools:context=".ActivityHome" >

<ImageView
    android:id="@+id/imgView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="0dp"
    android:scaleType="fitXY"
/>

【问题讨论】:

    标签: android image gridview fullscreen onclicklistener


    【解决方案1】:

    创建一个新的布局:

    <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"
    android:orientation="vertical"
    tools:context=".ActivityHome" >
    
    <ImageView
    android:id="@+id/imgView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="0dp"
    android:scaleType="fitXY" //the image will be stretched to fit all the sides of the ImageView 
    android:scaleType="centerInside" //if you want to keep the resolution use
    />
    </RelativeLayout>
    

    通过点击调用调用此活动

    Intent myintent=new Intent(currentActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", value);
    startActivity(myintent);
    

    FullscreenImageView类中:

    String imageURL = getIntent().getStringExtra("SelectedImageURL");
    

    在您将项目添加到网格视图的方法中:

    gridView.setOnItemClickListener(new OnItemClickListener() {
    
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
                //code goes here to get the image url based on the position 
        }
    });
    

    【讨论】:

    • 你没有在我的帖子中添加点击监听器等?我的意思是将它添加到我的代码中,因为我不知道将它放在哪里(我添加了新的布局 xml)但我不知道从那里去哪里
    • 可以放在mGridView.setAdapter(adapter);前面
    • 好的,我将代码编辑为我现在拥有的代码,但我在 gridView、currentActivity 和侦听器中的主要活动中得到“无法解析符号”,在全屏类的 getIntent 上也是如此?再次感谢我对此表示赞赏
    • 你的FullscreenImageView 类应该是extends Activity@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.FullScreenLayout); Bundle bundle = getIntent().getExtras(); final String SelectedImageURL = bundle.getString("SelectedImageURL"); ...... }
    • 别忘了把&lt;activity android:name="com.package.project.FullScreenImage" android:icon="@drawable/ic_launcher" android:label="@string/app_name" /&gt; 添加到你的主节目中
    猜你喜欢
    • 1970-01-01
    • 2015-03-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    相关资源
    最近更新 更多