Переместить анимацию, чтобы появились другие виды

Я использую TranslateAnimation, чтобы сделать фрагмент (GoogleMap), скользящим вниз, чтобы освободить место для EditText и TextView, чтобы они были видны. поэтому я использовал это:

текст: текстовый вид

редактировать: EditText

MapLayout: LinearLayout, содержащий карту

Animation animation = new TranslateAnimation(
MapLayout.getX(), MapLayout.getY(),MapLayout.getY(), text.getHeight()+edit.getHeight());

Проблема в том, что я не могу сделать слайд, потому что text.getHeight()+edit.getHeight() возвращает 0, поэтому слайда нет! Я попытался использовать число (например, 100), слайд создан, но он отличается между устройствами, я тестировал на Galaxy S3, и слайд не завершен, часть EditText все еще не видна, что касается эмулятор работал нормально. Когда я попытался сделать число немного больше, чтобы слайд был длиннее (например, 200), ну... слайд был хорош для S3, но я был большим для эмулятора.

Итак, что я хочу знать, так это то, что если есть какой-либо способ заставить слайд двигаться в точку, не завися от устройства, я имею в виду без использования пикселей; так что слайд будет отлично работать на любом устройстве/

Я надеюсь, что моя проблема ясна. Спасибо

Обновление: я не знаю, если это поможет, я добавил сообщение Toast, показываю высоту EditText и TextView, в эмуляторе он говорит: 85, а в S3 он говорит: 181 Так что да, мне нужно сделать карту сдвиньте вниз на любом устройстве, как я сказал

Основная деятельность:

protected Animation animation;
    protected LinearLayout MapLayout;
    protected EditText edit;
    protected TextView text;

    MapLayout = (LinearLayout)findViewById(R.id.MapLayout);
    edit = (EditText)findViewById(R.id.Recherche);
    text = (TextView)findViewById(R.id.CaptionRecherche);
    Toast.makeText(context, "Height: "+(edit.getHeight()+text.getHeight()), 1000).show();
    animation = new TranslateAnimation(MapLayout.getX(), MapLayout.getY(), MapLayout.getY(), text.getHeight()+edit.getHeight());
    animation.setDuration(1000);
    animation.setFillAfter(true);
    MapLayout.startAnimation(animation);

Основной XML:

------- Я использую DrawerLayout... У меня есть слайд-меню, которое можно показать в приложении... просто для информации -------

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DrawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <include
        android:id="@+id/ContenuPrincipal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        layout="@layout/activity_main_relative"
        />
    <!-- ListView... La liste des options du menu -->
       <ListView
            android:id="@+id/Menu"
            android:layout_width="250dp"
            android:layout_height="fill_parent"
            android:choiceMode="singleChoice"
            android:layout_gravity="start"
            android:background="#333"
            android:divider="#666"
            android:dividerHeight="1dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            />

</android.support.v4.widget.DrawerLayout>

Main2 XML (тот, который я включил выше):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="#E8E8E8">

            <!-- Champs de saisie pour effectuer la recherche:  -->

        <TextView
            android:id="@+id/CaptionRecherche"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Entrer l'emplacement que vous cherchez: "
            android:textSize="20sp"
            android:layout_marginTop="7dp"
            android:layout_marginLeft="20dp"
            />
        <EditText
            android:id="@+id/Recherche"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp"
            android:hint="Salle, Deparetement..."
            android:layout_marginLeft="20dp"
            android:layout_marginBottom="20dp"
            android:maxLength="100"
            android:maxLines="1" 
            android:layout_below="@id/CaptionRecherche"/>

                <!-- La map:  -->
     <LinearLayout
         android:id="@+id/MapLayout"
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent"
         >

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
             />

    </LinearLayout>
</RelativeLayout>

person Tha.Poox    schedule 18.02.2014    source источник


Ответы (1)


Как часть моего приложения, у меня есть строка состояния, содержащая некоторый текст. Эта строка состояния скрыта до тех пор, пока пользователь не нажмет кнопку, после чего она сдвинется вниз (скрывая самое верхнее содержимое макета ниже).

Код, который я использую, чтобы получить правильную высоту скрытой строки состояния:

private int hiddenStatusHeight;
private int currentStatusBarHeight;

private void getStatusBarHeight() {
    final ViewTreeObserver observer = hiddenStatus.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override public void onGlobalLayout() {

            hiddenStatus.measure(MeasureSpec.UNSPECIFIED,
                    MeasureSpec.UNSPECIFIED);
            hiddenStatusHeight = hiddenStatus.getMeasuredHeight();

            currentStatusBarHeight = statusBar.getHeight();

            ViewTreeObserver obs = hiddenStatus.getViewTreeObserver();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                obs.removeOnGlobalLayoutListener(this);
            } else {
                obs.removeGlobalOnLayoutListener(this);
            }
        }
    });
}

Код, который выполняется при нажатии кнопки:

private OnClickListener ExpandClickListener = new OnClickListener() {

    @Override public void onClick(View v) {
        boolean isExpanded = (Boolean) expandButton
                .getTag(R.id.TAG_EXPANDED);
        int originalHeight = (Integer) expandButton
                .getTag(R.id.TAG_ORIGINAL_HEIGHT);

        if (isExpanded) {
            expandButton.setTag(R.id.TAG_EXPANDED, false);
            expandButton.setImageResource(R.drawable.ic_action_down);
            // statusBar.setLayoutParams(new FrameLayout.LayoutParams(
            // LayoutParams.MATCH_PARENT, originalHeight));
            Log.d(TAG, "Collapsing to " + originalHeight);
            ValueAnimator va = ValueAnimator.ofInt(currentStatusBarHeight,
                    originalHeight);
            va.setDuration(500);
            va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                public void onAnimationUpdate(ValueAnimator animation) {
                    Integer value = (Integer) animation.getAnimatedValue();
                    statusBar.getLayoutParams().height = value.intValue();
                    statusBar.requestLayout();
                }
            });
            va.start();
        } else {
            expandButton.setTag(R.id.TAG_EXPANDED, true);
            expandButton.setImageResource(R.drawable.ic_action_collapse);
            currentStatusBarHeight = originalHeight + hiddenStatusHeight;
            // statusBar.setLayoutParams(new FrameLayout.LayoutParams(
            // LayoutParams.MATCH_PARENT, currentStatusBarHeight + 15));
            Log.d(TAG, "Expanding to " + originalHeight + "+"
                    + hiddenStatusHeight + "=" + currentStatusBarHeight);
            ValueAnimator va = ValueAnimator.ofInt(originalHeight,
                    currentStatusBarHeight);
            va.setDuration(500);
            va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                public void onAnimationUpdate(ValueAnimator animation) {
                    Integer value = (Integer) animation.getAnimatedValue();
                    statusBar.getLayoutParams().height = value.intValue();
                    statusBar.requestLayout();
                }
            });
            va.start();
        }

    }
};

И, наконец, мой макет XML (это должен быть FrameLayout):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="70dp" >

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"
        android:orientation="vertical"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:showDividers="middle" >
    </LinearLayout>
</ScrollView>

<RelativeLayout
    android:id="@+id/displayStatusBar"
    style="@style/DisplayStatusBar"
    android:layout_width="match_parent"
    android:layout_height="65dp" >

    <RelativeLayout
        android:id="@+id/status_always_visible"
        style="@style/StatusBar"
        android:layout_width="match_parent"
        android:layout_height="20dp" >

        <TextView
            android:id="@+id/status_received"
            style="@style/StatusBarText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="@string/received" />

        <TextView
            android:id="@+id/status_time_received"
            style="@style/StatusBarText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/status_received" />

        <TextView
            android:id="@+id/status_time_delete_relative_text"
            style="@style/StatusBarText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/status_time_delete_relative"
            android:text="@string/is_deleted" />

        <TextView
            android:id="@+id/status_time_delete_relative"
            style="@style/StatusBarText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="@string/minutes" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/status_hidden"
        style="@style/StatusHidden"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/status_always_visible" >

        <LinearLayout
            android:id="@+id/status_hydrants_near_address_container"
            style="@style/StatusHiddenText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:divider="@android:drawable/divider_horizontal_bright"
            android:orientation="vertical"
            android:paddingLeft="10dp"
            android:showDividers="middle" >

            <TextView
                style="@style/StatusHiddenText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no_information" />
        </LinearLayout>
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/optionsBar"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="#999"
        android:orientation="horizontal"
        android:paddingTop="5dp" >

        <ImageButton
            android:id="@+id/button_hydrants"
            style="@style/android:Widget.ImageButton"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:alpha="50"
            android:contentDescription="@string/module_hydrants"
            android:src="@drawable/ic_action_place" />

        <ImageButton
            android:id="@+id/button_route"
            style="@style/android:Widget.ImageButton"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:contentDescription="@string/module_directions"
            android:src="@drawable/ic_action_directions" />

        <ImageButton
            android:id="@+id/button_pdf"
            style="@style/android:Widget.ImageButton"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:clickable="false"
            android:contentDescription="@string/module_accessplan"
            android:src="@drawable/ic_action_attachment" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <ImageButton
                android:id="@+id/button_more"
                style="@style/android:Widget.ImageButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:src="@drawable/ic_action_down" />

        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>

<!-- The "empty" view to show when there are no items in the "list" view defined above. -->

<TextView
    android:id="@android:id/empty"
    style="?android:textAppearanceSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:padding="32dp"
    android:text="@string/no_information"
    android:textColor="?android:textColorSecondary" />

</FrameLayout>

Надеюсь, что-то из этого может быть полезно для вас.

Просто чтобы упомянуть об этом, я задал аналогичный вопрос, когда видимый макет сдвигается вниз по мере расширения меню. Так что взгляните на это, если вы предпочитаете такое поведение: the-content-view-down/19098369#19098369">Как анимировать слайд в представлении уведомлений, который сдвигает представление содержимого вниз

Удачного кодирования

person cYrixmorten    schedule 18.02.2014