获取屏幕宽度,将view移出屏幕再移动回来

public class MainActivity extends AppCompatActivity {
   private TextView kuandu;
    float curTranslationX;
    float width;
    float height;
    private Button out;
    private Button in;
   private View view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        kuandu = (TextView) findViewById(R.id.kuandu);
        out = (Button) findViewById(R.id.out);
        in = (Button) findViewById(R.id.in);
        view =  findViewById(R.id.view);
        out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goOut();
            }
        });
        in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goIn();
            }
        });

        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        width = outMetrics.widthPixels;
        height = outMetrics.heightPixels;
        kuandu.setText("宽度是:" +width+ ",高度是" + height);

    }

    private void goOut() {
        curTranslationX = view.getTranslationX();
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", curTranslationX, width);
        animator.setDuration(1000);
        animator.start();

    }

    private void goIn() {
        curTranslationX = view.getTranslationX();
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", curTranslationX, 0);
        animator.setDuration(1000);
        animator.start();

    }


}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.laoyimou.imagetest.MainActivity">

    <Button
        android:id="@+id/out"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="out" />

    <Button
        android:id="@+id/in"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="in" />

    <TextView
        android:id="@+id/kuandu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="@color/colorPrimary" />


</LinearLayout>

 

posted @ 2018-01-12 11:33  劳猿外  阅读(705)  评论(0编辑  收藏  举报