Android用户界面-使用TransitionDrawable

时间:2018-06-30 01:58:27

标签: java android transitiondrawable

我想使用TransitionDrawable过渡一些图像。但是,TransitionDrawable仅允许两个图像。如何动态更改图像?

1 个答案:

答案 0 :(得分:0)

如果您要使用TransitionDrawable切换两个以上的图像,则可以执行以下操作。

这是我作为示例制作的测试程序:

public class MainActivity extends AppCompatActivity {
    private ImageView image;
    private TransitionDrawable trans;
    private Resources res;
    private int images[] = {R.drawable.yourImage1, R.drawable.yourImage2, R.drawable.yourImage3};
    private int imageIndex1;
    private int imageIndex2;

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

        ConstraintLayout layout = new ConstraintLayout(this);
        setContentView(layout);

        imageIndex1 = 0;
        imageIndex2 = 1;

        image = new ImageView(this);
        image.setImageResource(images[0]);
        layout.addView(image);

        res = this.getResources();

        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                trans = new TransitionDrawable(new Drawable[]{res.getDrawable(images[imageIndex1]), res.getDrawable(images[imageIndex2])});
                if (imageIndex1 == images.length-1) {
                    imageIndex1 = 0;
                } else {
                    imageIndex1++;
                }
                if (imageIndex2 == images.length-1) {
                    imageIndex2 = 0;
                } else {
                    imageIndex2++;
                }

                image.setImageDrawable(trans);

                // Set the parameter value to whatever time you want
                trans.reverseTransition(2000);
            }
        });
    }
}

我希望这与您要寻找的东西相似。