LinearLayout使用不带XML的Java代码动态设置边框颜色 [英] LinearLayout set border color dynamically using java code without XML

查看:347
本文介绍了LinearLayout使用不带XML的Java代码动态设置边框颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对该问题进行了一些研究,但是我还没有发现类似的东西.

I have done some research on that issue , but I have not found anything similar just yet.

首先,我使用ShapeDrawable制作Linear Layout的边框,然后尝试在LinearLayout上设置背景颜色,但未设置颜色,然后注释了ShapeDrawable的两行,然后在设置Linear Layout的背景颜色后出现了问题边框颜色.

First I make a border of Linear Layout using ShapeDrawable then I have try to set background color on LinearLayout but color is not set then I have comment two line of ShapeDrawable then after I have set the background color of Linear Layout but problem occur in border color.

这是我通过背景色和边框色的JSON获得的价值.

That's value I have got through JSON of background color and border color.

我想通过Java代码动态设置该值.

I want to set that value dynamically Background color and border color of Linear Layout through java code.

请引导我.

谢谢

LinearLayout linearToAdd = new LinearLayout(getActivity());
linearToAdd.setOrientation(VERTICAL);
float d = getActivity().getResources().getDisplayMetrics().density;

  linearToAdd.setBackgroundColor(Color.parseColor((String)(mPod.getBackground())));

    switch(parentType){
    case LINEAR_LAYOUT:
        LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams((int)(mPod.getWidth()*d),(int)(mPod.getHeight()*d));
        Log.d(TAG,"LinLay, W,H,T,L: "+mPod.getWidth()+", "+mPod.getHeight()+", "+mPod.getLeft()+", "+mPod.getTop());
        linearParams.setMargins(mPod.getLeft(), mPod.getTop(), 0,0);            
        linearToAdd.setLayoutParams(linearParams);

               ShapeDrawable rectShapeDrawable1 = new ShapeDrawable();
               Paint paint1 = rectShapeDrawable1.getPaint();
        //     paint1.setColor(Color.rgb(0, 0, 0));
               paint1.setStyle(Paint.Style.STROKE);
               paint1.setStrokeWidth(3);

        //     linearToAdd.setBackgroundDrawable(rectShapeDrawable1);

               break;
    } 

推荐答案

您可以尝试通过GradientDrawable进行操作.我尝试了这个.希望对您有帮助.

You can try doing it by GradientDrawable. I tried this one. Hope it might help you.

GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStroke(3, Color.BLACK);
drawable.setCornerRadius(8);
drawable.setColor(Color.BLUE);
linearToAdd.setBackgroundDrawable(drawable);

在您的XML布局中,将android:padding ="1dp"设置为linearToAdd.

In your XML layout give android:padding="1dp" to linearToAdd.

这篇关于LinearLayout使用不带XML的Java代码动态设置边框颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆