Android samples API Demos之UI篇2(ActivitySceneTransitionBasic)

来源:互联网 发布:福赛大学 知乎 编辑:程序博客网 时间:2024/06/05 22:57

Android ActivitySceneTransitionBasic Sample

This sample shows how to use scene transitions from one Activity to another in Lollipop. Uses a combination of changeImageTransform and changeBounds to transition a grid of images to an Activity with a large image and detail text.
此示例演示如何在Lollipop中从一个Activity中使用场景切换到另一个Activity,使用changeImageTransform 和 changeBounds 的组合函数实现从文本图像网格视图Activity过渡到大图像。

//今天一直没有足够的时间写,换台电脑环境不同了,明天补全些

已经过了一天,今天补全

<pre style="font-family: 宋体; font-size: 11.3pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">public class MainActivity extends Activity implements AdapterView.OnItemClickListener {    private GridView mGridView;    private GridAdapter mAdapter;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.grid);        // Setup the GridView and set the adapter        mGridView = (GridView) findViewById(R.id.grid);        mGridView.setOnItemClickListener(this);        mAdapter = new GridAdapter();        mGridView.setAdapter(mAdapter);    }    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {        Item item = (Item) adapterView.getItemAtPosition(position);        // Construct an Intent as normal        Intent intent = new Intent(this, DetailActivity.class);        intent.putExtra(DetailActivity.EXTRA_PARAM_ID, item.getId());
//这里就是为什么整个应用可以产生跳转动画的原因,整理设置了一个ActivityOptionsCompat.makeSceneTransitionAnimation,从而产生了伸缩动画</span>        ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(                this,                // Now we provide a list of Pair items which contain the view we can transitioning                // from, and the name of the view it is transitioning to, in the launched activity                new Pair<View, String>(view.findViewById(R.id.imageview_item),                        DetailActivity.VIEW_NAME_HEADER_IMAGE),                new Pair<View, String>(view.findViewById(R.id.textview_name),                        DetailActivity.VIEW_NAME_HEADER_TITLE));        // Now we can start the Activity, providing the activity options as a bundle        ActivityCompat.startActivity(this, intent, activityOptions.toBundle());    }    /**     * {@link android.widget.BaseAdapter} which displays items.     */    private class GridAdapter extends BaseAdapter {        @Override        public int getCount() {            return Item.ITEMS.length;        }        @Override        public Item getItem(int position) {            return Item.ITEMS[position];        }        @Override        public long getItemId(int position) {            return getItem(position).getId();        }        @Override        public View getView(int position, View view, ViewGroup viewGroup) {            if (view == null) {                view = getLayoutInflater().inflate(R.layout.grid_item, viewGroup, false);            }            final Item item = getItem(position);            // Load the thumbnail image            ImageView image = (ImageView) view.findViewById(R.id.imageview_item);            Picasso.with(image.getContext()).load(item.getThumbnailUrl()).into(image);            // Set the TextView's contents            TextView name = (TextView) view.findViewById(R.id.textview_name);            name.setText(item.getName());            return view;        }    }}
下面这个是跳转到的Activity,也就是详细视图
package com.example.android.activityscenetransitionbasic;import com.squareup.picasso.Picasso;import android.app.Activity;import android.os.Build;import android.os.Bundle;import android.support.v4.view.ViewCompat;import android.transition.Transition;import android.widget.ImageView;import android.widget.TextView;/** * Our secondary Activity which is launched from {@link MainActivity}. Has a simple detail UI * which has a large banner image, title and body text. */public class DetailActivity extends Activity {    // Extra name for the ID parameter    public static final String EXTRA_PARAM_ID = "detail:_id";    // View name of the header image. Used for activity scene transitions    public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";    // View name of the header title. Used for activity scene transitions    public static final String VIEW_NAME_HEADER_TITLE = "detail:header:title";    private ImageView mHeaderImageView;    private TextView mHeaderTitle;    private Item mItem;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.details);        // Retrieve the correct Item instance, using the ID provided in the Intent        mItem = Item.getItem(getIntent().getIntExtra(EXTRA_PARAM_ID, 0));        mHeaderImageView = (ImageView) findViewById(R.id.imageview_header);        mHeaderTitle = (TextView) findViewById(R.id.textview_title);        /**         * Set the name of the view's which will be transition to, using the static values above.         * This could be done in the layout XML, but exposing it via static variables allows easy         * querying from other Activities         *///这个地方设置了动画效果        ViewCompat.setTransitionName(mHeaderImageView, VIEW_NAME_HEADER_IMAGE);        ViewCompat.setTransitionName(mHeaderTitle, VIEW_NAME_HEADER_TITLE);        loadItem();    }    private void loadItem() {        // Set the title TextView to the item's name and author        mHeaderTitle.setText(getString(R.string.image_header, mItem.getName(), mItem.getAuthor()));//如果版本支持动画效果的话,就先显示缩略图(同时设置动画效果结束后的操作),不然的话,直接显示大图        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && addTransitionListener()) {            // If we're running on Lollipop and we have added a listener to the shared element            // transition, load the thumbnail. The listener will load the full-size image when            // the transition is complete.            loadThumbnail();        } else {            // If all other cases we should just load the full-size image now            loadFullSizeImage();        }    }    /**     * Load the item's thumbnail image into our {@link ImageView}.     */    private void loadThumbnail() {        Picasso.with(mHeaderImageView.getContext())                .load(mItem.getThumbnailUrl())                .noFade()                .into(mHeaderImageView);    }    /**     * Load the item's full-size image into our {@link ImageView}.     */    private void loadFullSizeImage() {        Picasso.with(mHeaderImageView.getContext())                .load(mItem.getPhotoUrl())                .noFade()                .noPlaceholder()                .into(mHeaderImageView);    }    /**     * Try and add a {@link Transition.TransitionListener} to the entering shared element     * {@link Transition}. We do this so that we can load the full-size image after the transition     * has completed.     *     * @return true if we were successful in adding a listener to the enter transition     *///设置监听,一旦动画结束,显示大图    private boolean addTransitionListener() {        final Transition transition = getWindow().getSharedElementEnterTransition();        if (transition != null) {            // There is an entering shared element transition so add a listener to it            transition.addListener(new Transition.TransitionListener() {                @Override                public void onTransitionEnd(Transition transition) {                    // As the transition has ended, we can now load the full-size image                    loadFullSizeImage();                    // Make sure we remove ourselves as a listener                    transition.removeListener(this);                }                @Override                public void onTransitionStart(Transition transition) {                    // No-op                }                @Override                public void onTransitionCancel(Transition transition) {                    // Make sure we remove ourselves as a listener                    transition.removeListener(this);                }                @Override                public void onTransitionPause(Transition transition) {                    // No-op                }                @Override                public void onTransitionResume(Transition transition) {                    // No-op                }            });            return true;        }        // If we reach here then we have not added a listener        return false;    }}

布局文件中使用了自定义的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:orientation="vertical">    <com.example.android.activityscenetransitionbasic.SquareFrameLayout          android:layout_width="match_parent"          android:layout_height="wrap_content">        <ImageView              android:id="@+id/imageview_item"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:scaleType="centerCrop" />    </com.example.android.activityscenetransitionbasic.SquareFrameLayout>    <TextView          android:id="@+id/textview_name"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:background="?android:attr/colorPrimary"          android:theme="@android:style/Theme.Material"          android:textAppearance="@android:style/TextAppearance.Material.Subhead"          android:maxLines="1"          android:padding="16dp" /></LinearLayout>
下面说一说这个自定义布局SquareFrameLayout:详细一点的,大家可以看这个:http://blog.csdn.net/u012604322/article/details/17093421
public class SquareFrameLayout extends FrameLayout {
<span style="font-family: Arial;">...</span>
<pre name="code" class="java"> protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);        if (widthSize == 0 && heightSize == 0) {            // If there are no constraints on size, let FrameLayout measure            super.onMeasure(widthMeasureSpec, heightMeasureSpec);            // Now use the smallest of the measured dimensions for both dimensions            final int minSize = Math.min(getMeasuredWidth(), getMeasuredHeight());            setMeasuredDimension(minSize, minSize);            return;        }        final int size;        if (widthSize == 0 || heightSize == 0) {            // If one of the dimensions has no restriction on size, set both dimensions to be the            // on that does            size = Math.max(widthSize, heightSize);        } else {            // Both dimensions have restrictions on size, set both dimensions to be the            // smallest of the two            size = Math.min(widthSize, heightSize);        }        final int newMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);        super.onMeasure(newMeasureSpec, newMeasureSpec);    }}
/*1.View本身大小多少,这由onMeasure()决定;
2.View在ViewGroup中的位置如何,这由onLayout()决定;
3.绘制View,onDraw()定义了如何绘制这个View。*/<pre style="background-color: rgb(255, 255, 255); font-family: 宋体; font-size: 9pt;"> 截图:




0 0
原创粉丝点击