2016-11-18 1 views
0

Попытка переместить ImageView объектов вокруг по отношению к другим ImageView объектов, но координаты, которые я получаю от getLocationOnScreen(int[]), не соответствуют тому, что на экране. Также один объект помещается над «родительским», а другой помещается под «родителем». настройка высоты app_bar_main также влияет на позиционирование. Мне сложно с этим справиться. Все, что я хочу, это один объект, который будет помещен посредине другого ... Пожалуйста, помогите.Есть ли лучший способ получить точное положение экрана объектов в оконном режиме?

FYI x coord работает нормально в портрете и LANDSCAPE, как ни странно.

Оба маркера используют один и тот же код, чтобы центрировать себя.

enter image description here

//Centers the position marker on the slider graphic 
public void centerSlider(){ 
    ImageView sliderPosition = (ImageView) rootview.findViewById(R.id.iv_slider_position); 
    int posXY[] = new int[2]; 
    rootview.findViewById(R.id.iv_slider).getLocationOnScreen(posXY); 
    int centerX = posXY[0] + ((rootview.findViewById(R.id.iv_slider)).getWidth()/2); 
    int centerY = posXY[1] - ((rootview.findViewById(R.id.iv_slider)).getHeight()/2); 
    sliderPosition.setX(centerX - (rootview.findViewById(R.id.iv_slider_position).getWidth()/2)); 
    sliderPosition.setY(centerY - (rootview.findViewById(R.id.iv_slider_position).getHeight()/2)); 
} 

Это Формуляром

<ImageView 
    android:layout_width="200dp" 
    android:layout_height="200dp" 
    app:srcCompat="@drawable/joystick3" 
    android:id="@+id/iv_joystick" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentRight="true"/> 

<ImageView 
    ads:srcCompat="@drawable/ball" 
    android:id="@+id/iv_joystick_position" 
    android:layout_height="50dp" 
    android:layout_width="50dp" 
    android:layout_alignBottom="@+id/iv_joystick" 
    android:layout_alignLeft="@+id/iv_joystick" 
    android:layout_marginBottom="5dp" 
    android:layout_centerInParent="false" /> 

<GridLayout 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginLeft="10dp" 
    android:layout_marginTop="10dp" 
    android:layout_width="wrap_content"> 

    <TextView 
     android:text="@string/live_damp_start" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/tv_damp_start" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_row="0" 
     android:layout_column="0" 
     android:textStyle="normal|bold" 
     android:textSize="14sp" 
     android:layout_columnSpan="2" /> 

    <SeekBar 
     android:layout_width="150dp" 
     android:layout_height="wrap_content" 
     android:id="@+id/sb_damp_start" 
     android:layout_row="1" 
     android:layout_column="0" 
     android:layout_columnSpan="2" /> 

    <TextView 
     android:text="@string/live_damp_end" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/tv_damp_end" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_row="2" 
     android:layout_column="0" 
     android:textSize="14sp" 
     android:textStyle="normal|bold" 
     android:layout_columnSpan="2" /> 

    <SeekBar 
     android:layout_width="150dp" 
     android:layout_height="wrap_content" 
     android:id="@+id/sb_damp_end" 
     android:layout_row="3" 
     android:layout_column="0" 
     android:layout_columnSpan="2" /> 

    <TextView 
     android:text="@string/invert" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/textView5" 
     android:textColor="@color/live_control_text_ui" 
     android:textStyle="normal|bold" 
     android:textSize="15sp" 
     android:layout_column="0" 
     android:layout_row="4" /> 

    <CheckBox 
     android:text="@string/pan" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/checkBox" 
     android:layout_row="5" 
     android:layout_column="0" /> 

    <CheckBox 
     android:text="@string/tilt" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/checkBox2" 
     android:layout_row="6" 
     android:layout_column="0" /> 

    <CheckBox 
     android:text="@string/slide" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/checkBox3" 
     android:layout_row="7" 
     android:layout_column="0" /> 

    <TextView 
     android:text="@string/return_center" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/textView6" 
     android:textColor="@color/live_control_text_ui" 
     android:textStyle="normal|bold" 
     android:textSize="15sp" 
     android:layout_column="1" 
     android:layout_row="4" 
     android:layout_marginLeft="10dp" /> 

    <CheckBox 
     android:text="@string/pan" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/checkBox4" 
     android:layout_row="5" 
     android:layout_column="1" 
     android:layout_marginLeft="10dp" /> 

    <CheckBox 
     android:text="@string/tilt" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/checkBox5" 
     android:layout_row="6" 
     android:layout_column="1" 
     android:layout_marginLeft="10dp" /> 

    <CheckBox 
     android:text="@string/slide" 
     android:textColor="@color/live_control_text_ui" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/checkBox6" 
     android:layout_row="7" 
     android:layout_column="1" 
     android:layout_marginLeft="10dp" /> 

</GridLayout> 

<com.google.android.gms.ads.AdView 
    android:id="@+id/ad_view" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" 
    ads:adSize="SMART_BANNER" 
    ads:adUnitId="@string/banner_ad_unit_id" /> 

<ImageView 
    android:layout_width="500dp" 
    android:layout_height="60dp" 
    app:srcCompat="@drawable/slider3" 
    android:id="@+id/iv_slider" 
    android:layout_above="@+id/ad_view" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginBottom="70dp" /> 

<ImageView 
    ads:srcCompat="@drawable/ball" 
    android:id="@+id/iv_slider_position" 
    android:layout_height="50dp" 
    android:layout_width="50dp" 
    android:layout_alignBottom="@+id/iv_slider" 
    android:layout_alignLeft="@+id/iv_slider" 
    android:layout_marginBottom="5dp" 
    android:layout_centerInParent="false" /> 

</RelativeLayout> 
+0

использовать 'android: layout_gravity' then – pskink

+0

Если я не могу сделать ImageView родительским ImageView, это не сработает. Я рассмотрел этот вариант. Есть ли контейнер, который не приведет к тому, что «родительское» изображение будет масштабироваться за пределы экрана при обертывании вокруг него? – naps1saps

+0

чего вы хотите достичь на самом деле? возможно, какое-то изображение, описывающее? – pskink

ответ

0

Ну ... это начало. Вам нужно написать больше кода, чтобы получить ориентацию для добавления экранных системных кнопок, когда они расположены с левой стороны. Там должен быть более простой вариант, чем этот ... Я не собираюсь отмечать это еще, но я вижу, есть ли у кого лучший ответ для этого.

Мне все еще нужно учитывать аппаратные кнопки на экране, когда на левой стороне.

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

//Get system's status bar height 
public int getStatusBarHeight() { 
    int result = 0; 
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); 
    if (resourceId > 0) { 
     result = getResources().getDimensionPixelSize(resourceId); 
    } 
    return result; 
} 

Затем преобразовать размер дп вашей высоты панели инструментов, расположенной в app_bar_main.xml:

/** 
* This method converts dp unit to equivalent pixels, depending on device density. 
* 
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels 
* @param context Context to get resources and device specific display metrics 
* @return A float value to represent px equivalent to dp depending on device density 
*/ 
public static float convertDpToPixel(float dp, Context context){ 
    Resources resources = context.getResources(); 
    DisplayMetrics metrics = resources.getDisplayMetrics(); 
    float px = dp * ((float)metrics.densityDpi/DisplayMetrics.DENSITY_DEFAULT); 
    return px; 
} 

Что вы используете в следующем код: (я сделал его универсальным для всех, не забудьте изменить значение размера панели инструментов в вашем приложении)

public void centerObjectToParent(View parent, View child){ 
    //ImageView joystickPosition = (ImageView) rootview.findViewById(R.id.iv_joystick_position); 
    int posXY[] = new int[2]; 
    parent.getLocationInWindow(posXY); 
    int centerX = posXY[0] + (parent.getWidth()/2); 
    int centerY = posXY[1] + (parent.getHeight()/2); 
    child.setX(centerX - (child.getWidth()/2)); 
    child.setY(centerY - getStatusBarHeight() - convertDpToPixel(60, rootview.getContext()) - (child.getHeight()/2)); 
} 

Не могу поверить, насколько это оказалось трудным: -___-

Google необходимо исправить, чтобы получить код положения экрана, чтобы получить фактическое положение экрана после размещения.

0

Использование RelativeLayout с фоном вместо ImageView, похоже, избегает этих проблем, но не позволяет автоматически масштабировать изображение до соотношения сторон.

<RelativeLayout 
    android:layout_width="400dp" 
    android:layout_height="50dp" 
    android:background="@drawable/slider3" 
    android:id="@+id/layout_slider" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginTop="20dp"" /> 

Я бы хотел получить лучший ответ, если у кого-нибудь есть.

 Смежные вопросы

  • Нет связанных вопросов^_^