TextSwitch 和 ImageSwitch源码分析

这里写图片描述

               (Uml类图)

没有找到好的录制方式,比较low
这里写图片描述

1.主要处理,文字或者图片的切换(系统提供)
2.主要实现方式:通过interface ViewFactory的 makeView()进行View创建,然后需要调用XXswitcher的setText() / setImageResource()…,进行交换内容的填充。
3.支持给view设置自定义交换动画。
4.支持通过addview()添加交换的view

分析前一些疑问?

1.如何实现动画?

2.最多和最少可以添加多少个可交换view?

3.是否需要其他api的支持,才可以实现自动切换?是否可以控制开始/停止?

源码实现:这里分析TextSwitcher作为分析对象,ImageSwitcher 类似。

ViewSwitcher中ViewFactory用来创建View,需要

/**
 * Creates views in a ViewSwitcher.
 */
public interface ViewFactory {
    /**
     * Creates a new {@link android.view.View} to be added in a
     * {@link android.widget.ViewSwitcher}.
     *
     * @return a {@link android.view.View}
     */
    View makeView();
}
ViewSwitcher中setFactory( )
/**
 * Sets the factory used to create the two views between which the
 * ViewSwitcher will flip. Instead of using a factory, you can call
 * {@link #addView(android.view.View, int, android.view.ViewGroup.LayoutParams)}
 * twice.
 *
 * @param factory the view factory used to generate the switcher's content
 */
public void setFactory(ViewFactory factory) {
    mFactory = factory;
    obtainView();
    obtainView();
}

如何生成,代码就在obtainView()中

private View obtainView() {
        View child = mFactory.makeView(); //调用 makeView
        LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (lp == null) {
            lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }
        addView(child, lp);
        return child;
}

添加View的限制至多2个,否则会抛出异常;

/**
 * {@inheritDoc}
 *
 * @throws IllegalStateException if this switcher already contains two children
 */
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
    if (getChildCount() >= 2) {
        throw new IllegalStateException("Can't add more than 2 views to a ViewSwitcher");
    }
    super.addView(child, index, params);
}

分析如何实现动画?

ViewAnimator 中提供个设置in/out 动画的方法

这道这点就可以接着分析了。
从ViewAnimator的构造函数可以知道

public ViewAnimator(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ViewAnimator);
    int resource = a.getResourceId(com.android.internal.R.styleable.ViewAnimator_inAnimation, 0);
    if (resource > 0) {
        setInAnimation(context, resource);
    }

    resource = a.getResourceId(com.android.internal.R.styleable.ViewAnimator_outAnimation, 0);
    if (resource > 0) {
        setOutAnimation(context, resource);
    }

    boolean flag = a.getBoolean(com.android.internal.R.styleable.ViewAnimator_animateFirstView, true);
    setAnimateFirstView(flag);

    a.recycle();

    initViewAnimator(context, attrs);
}

知道TextSwitcher 支持xml配置动画资源,同时支持调用方法设置。

而且可以发现重新FramLayout 的addview( )方法,是关键点。最后调用
setDisplayedChild();

@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
    super.addView(child, index, params);
    if (getChildCount() == 1) {
        child.setVisibility(View.VISIBLE);
    } else {
        child.setVisibility(View.GONE);
    }
    if (index >= 0 && mWhichChild >= index) {
        // Added item above current one, increment the index of the displayed child
        setDisplayedChild(mWhichChild + 1);
    }
}

判断显示的childview是否超出范围,清除旧focus。

/**
 * Sets which child view will be displayed.
 *
 * @param whichChild the index of the child view to display
 */
@android.view.RemotableViewMethod
public void setDisplayedChild(int whichChild) {
    mWhichChild = whichChild;
    if (whichChild >= getChildCount()) {
        mWhichChild = 0;
    } else if (whichChild < 0) {
        mWhichChild = getChildCount() - 1;
    }
    boolean hasFocus = getFocusedChild() != null;
    // This will clear old focus if we had it
    showOnly(mWhichChild);
    if (hasFocus) {
        // Try to retake focus if we had it
        requestFocus(FOCUS_FORWARD);
    }
}

/**
 * Shows only the specified child. The other displays Views exit the screen
 * with the {@link #getOutAnimation() out animation} and the specified child
 * enters the screen with the {@link #getInAnimation() in animation}.
 *
 * @param childIndex The index of the child to be shown.
 */
void showOnly(int childIndex) {
    final boolean animate = (!mFirstTime || mAnimateFirstTime);
    showOnly(childIndex, animate);
}

/**
 * Shows only the specified child. The other displays Views exit the screen,
 * optionally with the with the {@link #getOutAnimation() out animation} and
 * the specified child enters the screen, optionally with the
 * {@link #getInAnimation() in animation}.
 *
 * @param childIndex The index of the child to be shown.
 * @param animate Whether or not to use the in and out animations, defaults
 *            to true.
 */
void showOnly(int childIndex, boolean animate) {
    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (i == childIndex) {
            if (animate && mInAnimation != null) {
                child.startAnimation(mInAnimation);
            }
            child.setVisibility(View.VISIBLE);
            mFirstTime = false;
        } else {
            if (animate && mOutAnimation != null && child.getVisibility() == View.VISIBLE) {
                child.startAnimation(mOutAnimation);
            } else if (child.getAnimation() == mInAnimation)
                child.clearAnimation();
            child.setVisibility(View.GONE);
        }
    }
}

Ok看到showOnly这个方法基本上就可以确定如何进行动画显示与移除了,for循环,判断childIndex为第几个child就为第几个view添加动画,前提是设置了动画(在xml中或者调用set方法)
再看第三个问题 自动切换?

/**
 * Sets the text of the next view and switches to the next view. This can
 * be used to animate the old text out and animate the next text in.
 *
 * @param text the new text to display
 */
public void setText(CharSequence text) {
    final TextView t = (TextView) getNextView();
    t.setText(text);
    showNext();
}

/**
 * Returns the next view to be displayed.
 *
 * @return the view that will be displayed after the next views flip.
 */
public View getNextView() {
    int which = mWhichChild == 0 ? 1 : 0;
    return getChildAt(which);
}
/**
 * Manually shows the next child.
 */
@android.view.RemotableViewMethod
public void showNext() {
    setDisplayedChild(mWhichChild + 1);
}

调用setDisplayedChild()进行展示并且设置动画效果,当然看到这里可以知道,只有重复的设置setText()才可以实现动画效果可以Text的内容。
网上的大部分的解决方案是使用Timer添加计时器,定时去设置setText(),想要停止就去控制Timer.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Android中,可以使用Gallery和ImageSwitcher来实现可左右循环滑动的图片浏览器。 首先,在布局文件中添加一个Gallery和一个ImageSwitcher: ``` <Gallery android:id="@+id/gallery" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:gravity="center_vertical" /> <ImageSwitcher android:id="@+id/imageSwitcher" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/gallery" /> ``` 然后,在Java代码中,需要为Gallery设置一个Adapter,并为ImageSwitcher设置一个ViewFactory。代码如下: ``` public class MainActivity extends AppCompatActivity { private Gallery mGallery; private ImageSwitcher mImageSwitcher; private int[] mImageIds = new int[]{R.drawable.image1, R.drawable.image2, R.drawable.image3}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGallery = (Gallery) findViewById(R.id.gallery); mImageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher); mGallery.setAdapter(new ImageAdapter(this)); mImageSwitcher.setFactory(new ViewFactory() { @Override public View makeView() { ImageView imageView = new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); return imageView; } }); mGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mImageSwitcher.setImageResource(mImageIds[position % mImageIds.length]); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context context) { mContext = context; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new Gallery.LayoutParams(200, 200)); imageView.setScaleType(ImageView.ScaleType.FIT_XY); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mImageIds[position % mImageIds.length]); return imageView; } } } ``` 这里的关键是设置Gallery的Adapter为一个无限循环的Adapter,以及在Gallery的OnItemSelectedListener中更新ImageSwitcher的图片资源。同时,ImageAdapter负责为Gallery提供每个Item的View。 这样,我们就可以实现一个左右循环滑动的图片浏览器了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灯塔@kuaidao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值