ontouchlistener无法正常工作

时间:2016-06-15 21:40:51

标签: java android ontouchlistener

我的形象在奇怪地移动并且在随意的时刻暂停,而我需要它是连续的。它停止然后工作。如果你能提高效率,请发帖。另外看看是否有办法缩短代码。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public int x;
public float g =10.0f;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView iconss = (ImageView) findViewById(R.id.craft);
        final Button button1 = (Button) findViewById(R.id.left);
        final TextView txt1 = (TextView)findViewById(R.id.fail);
        final Button button2 = (Button) findViewById(R.id.Right);

        button2.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v) {
                g = g + 10f;
                x = 1;

                final CharSequence work;
                work = "it is working";
                txt1.setText(work);

                iconss.setTranslationX(g);
            }

        });

        button2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v,MotionEvent event) {
                g = g + 10f;
                x = 1;

                final CharSequence work;
                work = "it is working";
                txt1.setText(work);

                iconss.setTranslationX(g);

                return false;
            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                g = g - 10f;
                x = 1;

                final CharSequence work;
                work = "it is working";
                txt1.setText(work);

                iconss.setTranslationX(g);
            }
        });

        button1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v,MotionEvent event) {
                g = g - 10f;
                x = 1;

                final CharSequence work;
                work = "it is working";
                txt1.setText(work);

                iconss.setTranslationX(g);

                return false;
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

ClickEvent和TouchEvent之间的问题不明确。

您应该删除TouchListener并将其替换为动画

  1. 计算图像移动到的目标位置

  2. 设置过渡时间

  3. 单击按钮时启动动画