【问题标题】:Animate LinearLayout when keyboard goes up/down键盘向上/向下时动画线性布局
【发布时间】:2015-09-22 03:46:42
【问题描述】:

我有这样的布局:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="25dp"
    android:paddingRight="25dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:background="@drawable/logo" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView ... />

            <EditText ... />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView ... />

            <EditText ... />

        </LinearLayout>

    </LinearLayout>

    <Button ... />

</LinearLayout>

我想在键盘弹起时淡出ImageView 并向上移动第二个(内部)LinearLayout(靠近屏幕顶部),然后在键盘放下时执行相反的操作。

我怎样才能做到这一点?

【问题讨论】:

    标签: android android-layout android-activity android-xml


    【解决方案1】:

    使用 TranslateAnimation 类为您的视图设置动画。

    Animation slide = new TranslateAnimation(fromX,toX,fromY,toY);
    slide.setDuration(300);//here you can set your own duration of animation in ms.
    yourView.startAnimation(slide);
    

    您还可以覆盖一些回调。

    slide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
    
            }
            @Override
            public void onAnimationEnd(Animation animation) {
    
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
    
            }
        });
    

    没有直接的方法可以确定 android 软键盘是否可用。但是您可以解决并计算活动的视图根和窗口大小之间的大小差异。有很多方法可以做到这一点,我发现的一种方法是:

        final View activityRootView = findViewById(R.id.activityRoot);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
                ... do something here
            }
         }
    });
    

    【讨论】:

    • 如何检查键盘是否向上/向下?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多