2

Я программирую активность Android, и он должен иметь фон с цветом в верхней части и другой цвет в нижней части.Два цвета фона Android

Относительная компоновка используется с прокладкой.

То, что я обычно делаю, это использовать не проложенную относительную компоновку и делить ее в верхнем и нижнем относительном расположении, эти u/l делятся на другую дополненную относительную компоновку.

Это заверяет меня, что вся область деятельности имеет цвет фона, который он должен иметь. Проложенная область гарантирует, что виджеты расположены вокруг центра деятельности.

Но теперь у меня есть уже запрограммированная активность, а верхние боковые виджеты и нижняя сторона связаны друг с другом, поэтому я не могу легко разделить относительный макет.

Любые советы?

+0

верхний цвет занимает 50% экрана и нижний 50%? –

+0

Я думаю, что это примерно 40/60 – EagleOne

+0

Хорошо, дайте mi минута :) –

ответ

1

Посмотрите на этот макет для своей деятельности. Существует только один RelativeLayout с двумя фонов. Один из них настроен на сам макет, другой - на пустой View, который расположен под видами сверху. Единственный недостаток - вы должны удалить padding из RelativeLayout и заменить его margin, установленным на ваши взгляды. Думаю, это не так уж и важно.

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

    <!-- This is the last TextView of top part, below it the bg will be different --> 
    <TextView 
     android:id="@+id/top_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_margin="16dp" 
     android:text="This represents top elements"/> 

    <!-- This View must be placed before any elements from the bottom part --> 
    <View 
     android:id="@+id/bottom_background" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/top_text" 
     android:layout_alignParentBottom="true" 
     android:background="#004892" /> 

    <!-- Now you can place your bottom elements and align them with the to ones --> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignTop="@id/bottom_background" 
     android:layout_alignLeft="@+id/top_text" 
     android:layout_marginTop="16dp" 
     android:textColor="#fff" 
     android:text="This is the bottom part"/> 

</RelativeLayout> 
+0

Работает! Ответ принят, отличная работа! – EagleOne

+0

Добро пожаловать! – Lamorak

+0

Только один последний вопрос: как мне реализовать поля? В первом относительном расположении? – EagleOne

2

Сначала добавьте это в ваш /values/attrs.xml. Если файл не существует, создайте его как тип ресурса.

<declare-styleable name="TwoColoredView"> 
    <attr name="topColor" format="color"/> 
    <attr name="bottomColor" format="color"/> 
    <attr name="topColorHeightPercent" format="integer"/> 
</declare-styleable> 

Далее создайте TwoColoredView класс и поместить его куда-нибудь, где вы храните свои собственные представления

import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Canvas; 
import android.graphics.Paint; 
import android.util.AttributeSet; 
import android.view.View; 

import your.package.R; 

/** 
* Created by Bojan on 27.4.2015. 
*/ 

public class TwoColoredView extends View { 

    private int measuredWidth, measuredHeight; 
    private Paint topPaint, bottomPaint; 
    final int defaultTopColor = 0xFFFF0000; 
    final int defaultBottomColor = 0xFF0000FF; 
    private int topHeight = 40; 

    public TwoColoredView(Context context) { 
     super(context); 
     init(context, null, 0); 
    } 

    public TwoColoredView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(context, attrs, 0); 
    } 

    public TwoColoredView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     init(context, attrs, defStyleAttr); 
    } 

    private void init(Context context, AttributeSet attributeSet, int style) { 

     TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.TwoColoredView, style, style); 

     int topColor = typedArray.getColor(R.styleable.TwoColoredView_topColor, defaultTopColor); 
     int bottomColor = typedArray.getColor(R.styleable.TwoColoredView_bottomColor, defaultBottomColor); 
     topHeight = typedArray.getInteger(R.styleable.TwoColoredView_topColorHeightPercent, 40); 

     typedArray.recycle(); 

     topPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     topPaint.setStyle(Paint.Style.FILL); 
     topPaint.setColor(topColor); 

     bottomPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     bottomPaint.setStyle(Paint.Style.FILL); 
     bottomPaint.setColor(bottomColor); 
    } 


    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

     measuredHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); 
     measuredWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); 

     setMeasuredDimension(measuredWidth, measuredHeight); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 

     canvas.drawRect(0, 0, measuredWidth, measuredHeight * 0.01f * topHeight, topPaint); 
     canvas.drawRect(0, measuredHeight * 0.01f * topHeight, measuredWidth, measuredHeight, bottomPaint); 
    } 
} 

Теперь создайте макет для вашего фрагмента/макета

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    > 

    <your.package.TwoColoredView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     app:topColorHeightPercent="40" 
     app:topColor="#FFFF0000" 
     app:bottomColor="#FF0000FF"/> 

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

     <!-- Other stuff goes here --> 

     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:gravity="center" 
      android:textColor="@android:color/white" 
      android:textSize="20sp" 
      android:text="Hehe.. I'm the middle bro!"/> 

    </RelativeLayout> 

</FrameLayout> 

И это окончательный

preview

+0

Пробовал, но «стиль не может быть разрешен или не является полем» – EagleOne

+0

Вам нужно добавить стиль к вашим attrs. Проверьте первый шаг. –

+0

Выполнено, но (ошибка: Неверный начальный тег declare-styleable \t attrs.xml) – EagleOne

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