📅  最后修改于: 2020-09-30 00:38:20             🧑  作者: Mango
Android图像切换器可在图像上提供动画,以从一个图像过渡到另一个图像。为了使用图像切换器,我们需要在.xml文件中实现ImageSwitcher组件。
ImageSwitcher的setFactory()方法提供ViewFactory接口的实现。 ViewFactory接口实现其未实现的方法并返回ImageView。
让我们实现一个图像切换器。
在布局文件夹中创建activity_main.xml和content_main.xml文件。
将一些图像放在可切换的文件夹中。
文件:activity_main.xml
文件:content_main.xml
文件:MainActivity.java
package com.example.test.imageswitcher;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import android.app.ActionBar;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
public class MainActivity extends AppCompatActivity {
ImageSwitcher imageSwitcher;
Button nextButton;
int imageSwitcherImages[] =
{R.drawable.cpp, R.drawable.c_sarp, R.drawable.jsp, R.drawable.mysql, R.drawable.hadoop};
int switcherImageLength = imageSwitcherImages.length;
int counter = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
nextButton = (Button) findViewById(R.id.button);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView switcherImageView = new ImageView(getApplicationContext());
switcherImageView.setLayoutParams(new ImageSwitcher.LayoutParams(
ActionBar.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.FILL_PARENT
));
switcherImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
switcherImageView.setImageResource(R.drawable.hadoop);
//switcherImageView.setMaxHeight(100);
return switcherImageView;
}
});
Animation aniOut = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
Animation aniIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
imageSwitcher.setOutAnimation(aniOut);
imageSwitcher.setInAnimation(aniIn);
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
if (counter == switcherImageLength){
counter = 0;
imageSwitcher.setImageResource(imageSwitcherImages[counter]);
}
else{
imageSwitcher.setImageResource(imageSwitcherImages[counter]);
}
}
});
}
}
输出量