从左到右和从右到左滑动图像

3
我正在开发一个应用程序,想要添加一个可以从左到右、从右到左滑动的图像,就像下面的图片一样。那个内部的白色播放图标应该从左向右移动,反之亦然。
我已经做了一些工作,能够将单个图像从左到右移动,反之亦然,但我希望设置背景图像,就像上面圆形黑色背景一样。
以下是我的代码:
imageView.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        int eid = event.getAction();
        switch (eid) {
        case MotionEvent.ACTION_MOVE:

            RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
            int x = (int) event.getRawX();
            mParams.leftMargin = x - 50;
            imageView.setLayoutParams(mParams);

            break;

        default:
            break;
        }
        return true;
    }
});

编辑

我尝试通过以下设置我的布局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" >

    <RelativeLayout
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        android:background="@drawable/set_user_profile_back"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/hello_world"
            android:src="@drawable/next" />
    </RelativeLayout>

</RelativeLayout>

但现在我面临的问题是图片大小,图片在右侧减小了,如何解决,并如何固定图像移动的起点和终点。

enter image description here

如果有任何想法和建议,将不胜感激。


@Shrikant 如何使图像从右向左移动? - Srikanth Pai
@juned 如何使图像从右向左移动? - Srikanth Pai
@contactmeandroid,您可以从这里下载XML文件:http://junedk.blogspot.com/2013/10/slide-image-from-left-to-right-and.html - Juned
@juned - 我想通过touchListner使图像从右向左移动,而不是使用动画,你有什么想法吗? - Srikanth Pai
您的上述代码在将图像放置在ParentLeft时完美运行,但当我将其放置在ParentRight时,它无法拖动。 - Srikanth Pai
显示剩余8条评论
1个回答

8

请尝试这段代码,Juned。

public class MainActivity extends Activity {

Button b1;
ImageView logo;
float width;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b1 = (Button) findViewById(R.id.button1);
    logo = (ImageView) findViewById(R.id.logo);

    Display display = getWindowManager().getDefaultDisplay();
    width = display.getWidth();
    final Animation posX = new TranslateAnimation(0, width - 50, 0, 0);
    posX.setDuration(1000);
    posX.setFillAfter(true);

    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            logo.startAnimation(posX);
            logo.setVisibility(View.VISIBLE);
        }
    });
}}

很棒的代码@shrikan,但是我如何在触摸事件中实现相同功能呢?正如我所描述的,我想拖动图片。 - Juned

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接