如何更改布局文件中可绘制形状的颜色

时间:2016-10-22 05:19:17

标签: android android-layout

我创造了一个可绘制的圆形形状。我使用它作为我的线性布局的背景。它工作正常。但问题是,我想创建6个不同颜色的圆圈。那么我只能使用一个可绘制的形状并为不同的圆圈改变颜色吗?

这是我的可绘制圆形

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>

<solid
    android:color="@color/colorPrimary"
    />
<size
    android:width="30dp"
    android:height="30dp"/>
</shape>

我想使用不同颜色的可绘制圆形创建此布局。

布局: enter image description here

4 个答案:

答案 0 :(得分:9)

您可以通过将相同的drawable(您提供的那个)设置为所有按钮,然后在您的代码中:

示例:

2016-10-21 21:56:21 [scrapy] INFO: Scrapy 1.1.0 started (bot: crowdfunder_crawl)
2016-10-21 21:56:21 [scrapy] INFO: Overridden settings: {'AJAXCRAWL_ENABLED': True, 'NEWSPIDER_MODULE': 'crowdfunder_crawl.spiders', 'SPIDER_MODULES': ['crowdfunder_crawl.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'crowdfunder_crawl'}
2016-10-21 21:56:21 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2016-10-21 21:56:21 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-10-21 21:56:21 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']

2016-10-21 21:56:21 [scrapy] INFO: Enabled item pipelines:
[]
2016-10-21 21:56:21 [scrapy] INFO: Spider opened

2016-10-21 21:56:21 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)

2016-10-21 21:56:21 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024

2016-10-21 21:56:21 [scrapy] DEBUG: Crawled (200) <GET https://www.crowdfunder.com/robots.txt> (referer: None)

2016-10-21 21:56:21 [scrapy] DEBUG: Redirecting (301) to <GET http://www.crowdfunder.com/user/login> from <GET https://www.crowdfunder.com/user/login/>

2016-10-21 21:56:22 [scrapy] DEBUG: Redirecting (301) to <GET https://www.crowdfunder.com/user/login> from <GET http://www.crowdfunder.com/user/login>

2016-10-21 21:56:22 [scrapy] DEBUG: Crawled (200) <GET https://www.crowdfunder.com/user/login> (referer: None)

2016-10-21 21:56:23 [scrapy] DEBUG: Crawled (200) <POST https://www.crowdfunder.com/user/signup> (referer: https://www.crowdfunder.com/user/login)

2016-10-21 21:56:23 [crowdfunder] DEBUG: login failed :( :( :(
2016-10-21 21:56:23 [scrapy] INFO: Closing spider (finished)
2016-10-21 21:56:23 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1569,
 'downloader/request_count': 5,
 'downloader/request_method_count/GET': 4,
 'downloader/request_method_count/POST': 1,
 'downloader/response_bytes': 16313,
 'downloader/response_count': 5,
 'downloader/response_status_count/200': 3,
 'downloader/response_status_count/301': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2016, 10, 22, 4, 56, 23, 232493),
 'log_count/DEBUG': 7,
 'log_count/INFO': 7,
 'request_depth_max': 1,
 'response_received_count': 3,
 'scheduler/dequeued': 4,
 'scheduler/dequeued/memory': 4,
 'scheduler/enqueued': 4,
 'scheduler/enqueued/memory': 4,
 'start_time': datetime.datetime(2016, 10, 22, 4, 56, 21, 180030)}
2016-10-21 21:56:23 [scrapy] INFO: Spider closed (finished)

为每个按钮执行此操作,但请记住将Drawable mDrawable = ContextCompat.getDrawable(context, R.drawable.yourDrawable); mDrawable.setColorFilter(new PorterDuffColorFilter(yourColorInt,PorterDuff.Mode.MULTIPLY)); final int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { yourButton.setBackgroundDrawable(mDrawable); } else { yourButton.setBackground(mDrawable); } 替换为您要应用的按钮所需的颜色。

答案 1 :(得分:3)

虽然@AbAppletic答案很好,但我想添加另一种方法来解决问题。您可以在java中定义圆形视图,然后在xml布局中多次使用此视图,并根据需要更改其颜色。 圆形视图:

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;


public class Circle extends View {

Paint p;
int color ;
public Circle(Context context) {
    this(context, null);
}

public Circle(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public Circle(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // real work here
    TypedArray a = context.getTheme().obtainStyledAttributes(
            attrs,
            R.styleable.Circle,
            0, 0
    );

    try {

        color = a.getColor(R.styleable.Circle_circleColor, 0xff000000);
    } finally {
        // release the TypedArray so that it can be reused.
        a.recycle();
    }
    init();
}

public void init()
{
    p = new Paint();
    p.setColor(color);
}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    if(canvas!=null)
    {
        canvas.drawCircle(getHeight()/2, getWidth()/2,getWidth()/2,p );
    }
}

}

attrs.xml中添加这些行:

<declare-styleable name="Circle">
        <attr name="circleRadius" format="integer"/>
        <attr name="circleColor" format="color" />
    </declare-styleable>

然后您可以多次在布局中使用此视图,也可以更改其背景:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TableRow android:gravity="center">

    <com.afranet.broadbandportal.view.Circle xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:background="@color/colorPrimary"
        app:circleColor="@color/color1" />

    <com.afranet.broadbandportal.view.Circle xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv2"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="5dp"
        android:background="@color/colorPrimary"
        app:circleColor="@color/color2" />

</TableRow>

<TableRow android:gravity="center">

    <com.afranet.broadbandportal.view.Circle xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv3"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="5dp"
        android:background="@color/colorPrimary"
        app:circleColor="@color/color3" />

    <com.afranet.broadbandportal.view.Circle xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv4"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="5dp"
        android:background="@color/colorPrimary"
        app:circleColor="@color/color4" />

</TableRow>

<TableRow android:gravity="center">

    <com.afranet.broadbandportal.view.Circle xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv5"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="5dp"
        android:background="@color/colorPrimary"
        app:circleColor="@color/color5" />

    <com.afranet.broadbandportal.view.Circle xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv6"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="5dp"
        android:background="@color/colorPrimary"
        app:circleColor="@color/color6" />

</TableRow>

以下是截图: enter image description here

答案 2 :(得分:1)

保持相同的形状并应用不同的app:backgroundTint

android:background="@drawable/shape"
app:backgroundTint="@color/blue"

请注意 app:(自定义命名空间)以获取更多信息 Android Layout - when to use app: vs android:?

答案 3 :(得分:0)

您现在可以使用backgroundTint标记更改可绘制形状的颜色(API级别21)

                android:backgroundTint="@color/yellow_color"