2015-09-01 2 views
0

Существует очень похожий вопрос здесь:Как выровнять edittext и кнопку рядом друг с другом внутри relativelayout?

How to put an EditText and Button next to each other?

Однако, этот вопрос имеет LinearLayout в качестве корневого элемента, и мой макет не делает.

Я также уже прочитал эту статью:

http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html

Что делает практически то же самое, что я хочу сделать, но мое устройство продолжает показывать кнопку на верхней из EditText элемента:

Button on top of EditText

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

    <EditText 
     android:id="@+id/editText" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:singleLine="true" 
     android:inputType="text" /> 

    <Button 
     android:id="@+id/search_button" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_alignEnd="@+id/editText" 
     android:layout_alignRight="@+id/editText" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:text="@string/search_button" /> 
</RelativeLayout> 

В идеале элемент EditText должен составлять около 75% ширины моего устройства, а кнопка остальная 25%

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

+0

я никогда tryit но новый AppCompat апите для относительного расположения в процентах, когда вы можете определить ширину и высоту в процентах попробовать. https://developer.android.com/tools/support-library/features.html#percent. или используйте linearlayout – mcd

+1

Другой пример вы можете найти здесь: http://www.mkyong.com/android/android-relativelayout-example/ –

ответ

1

Вместо этого вы должны использовать LinearLayout.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="match_parent"> 

    <EditText 
     android:id="@+id/editText" 
     android:layout_width="0dp" 
     android:weight="1" 
     android:layout_height="wrap_content" 
     android:singleLine="true" 
     android:inputType="text" /> 

    <Button 
     android:id="@+id/search_button" 
     android:layout_width="0dp" 
     android:weight="3" 
     android:layout_height="wrap_content"   
     android:text="@string/search_button" /> 
</LinearLayout > 

Edit: Альтернативное решение, но этот путь EditText фиксировано ширина и кнопки получить все остальные ширина

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

    <EditText 
     android:id="@+id/editText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:singleLine="true" 
     android:inputType="text" /> 

    <Button 
     android:id="@+id/search_button" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_toRightOf="@+id/editText" 
     android:layout_toEndOf="@+id/editText" 
     android:text="@string/search_button" /> 
</RelativeLayout> 
+0

Возможно, это связано с преждевременной оптимизацией, но сообщение разработчиков разработчиков android делает аргумент против использования ' LinearLayout', и они похожи на мой пример с помощью RelativeLayout. Есть ли какая-либо техническая функция, которая мешает мне использовать 'RelativeLayout' вместо' LinearLayout'? – ILikeTacos

+0

проверить альтернативный вариант размещения –

+1

на самом деле второе решение лучше, однако, если вы настаиваете на необходимости ** процентной ** ширины, вам может понадобиться LinearLayout, или вы можете попробовать заменить второе решение с помощью PercentageRelativeLayout. Однако не слишком доверяйте влиянию производительности. Аргумент воздействия на производительность начался несколько лет назад, и это еще не было проблемой в то время. Вы должны забыть об этом, если у вас нет более 3 или 4 слоев LinearLayout. –

0

использовать атрибут android:layout_toRightOf = "@id/editText" в Баттона и дать ширину починки на кнопку например:

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

    <EditText 
     android:id="@+id/editText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:singleLine="true" 
     android:ems = "15" 
     android:inputType="text" /> 

    <Button 
     android:id="@+id/search_button" 
     android:layout_width="60dp" 
     android:layout_height="wrap_content" 
     android:layout_toRightOf="@+id/editText" 
     android:text="@string/search_button" /> 
</RelativeLayout> 

Нам не нужно e дополнительные атрибуты, такие как android:layout_alignParentTop и т. д.

0

Прежде всего, вы дали fill_parent как ширину для обоих элементов. fill_parent означает же ширину, как родитель, поэтому они не могут быть выровнены по горизонтали (кстати, вы должны использовать match_parent вместо этого, они такие же, но бывшего устарели года назад ...). Чтобы они сидели рядом, вы должны сделать что-то вроде

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<!-- Put the Button first, so the EditText can occupy all the remaining space --> 
<Button 
    android:id="@+id/search_button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" 
    android:text="@string/search_button" /> 

<EditText 
    android:id="@+id/editText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_toStartOf="@id/search_button" 
    android:layout_toLeftOf="@id/search_button" 
    android:singleLine="true" 
    android:inputType="text" /> 

</RelativeLayout> 

К сожалению, у вас нет способа дать процент. Для достижения этой цели необходимо использовать LinearLayout и дать вес:

<LinearLayout 
android:orientation="horizontal" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<EditText 
    android:id="@+id/editText" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight=".75" 
    android:singleLine="true" 
    android:inputType="text" /> 

<Button 
    android:id="@+id/search_button" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight=".25" 
    android:text="@string/search_button" /> 

</LinearLayout> 
Смежные вопросы