Android:在LinearLayout上绘制边框

时间:2012-01-31 16:50:07

标签: android

我是Android新手。现在我有关于在LinearLayout上绘制边框的问题。我通过以下代码绘制边框。

   public class Borders{
    int w;
    int h;
    public Borders(int x, int y){
        w = x;
        h = y;
    }

    public void drawBorderInImg(Canvas canvas){
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(10);
        paint.setColor(Color.BLACK);
        canvas.drawLine(0, 0, w, 0, paint);
        canvas.drawLine(w, 0, w, h, paint);
        canvas.drawLine(w, h, 0, h, paint);
        canvas.drawLine(0, h, 0, 0, paint);
    }
}

我创建一个布尔值并使用onclickListener()来控制它。默认情况下,该值为false,因此屏幕上没有边框。

   @Override
        protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);
            // operate.refresh(ShapeData.figureList1);
            Borders borders = new Borders(img01.getWidth(), img01.getHeight());
            if(img01DrawOrNot){
                borders.drawBorderInImg(canvas);
            }

然后我做

img01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(img01DrawOrNot){
                    img01DrawOrNot = false;
                } else{
                    img01DrawOrNot = true;
                }
            }
        });

我在xml中设置 android:clickable = true 。它确实有效。但是,我需要postInvalidate()它。事实上,我无法刷新它因为它包含一些随机形状,当我执行postInvalidate()时,所有视图都会改变。它怎么会自动改变?因此,当我点击时,它会出现,当我再次点击时,它会消失。有人能帮助我吗?干杯!

1 个答案:

答案 0 :(得分:7)

如果你愿意,试试这个。

(在drawable文件夹中创建此布局) layout_border.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:height="2dp"
                android:color="#FF0000" />
            <solid android:color="#000000" />
            <padding android:left="1dp" android:top="1dp" android:right="1dp"
                android:bottom="1dp" />

            <corners android:radius="1dp" android:bottomRightRadius="5dp"
                android:bottomLeftRadius="0dp" android:topLeftRadius="5dp"
                android:topRightRadius="0dp" />
        </shape>
    </item>

</layer-list>

<强> main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="#ffffff"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    <LinearLayout android:layout_gravity="center"
    android:layout_width="200dp" android:layout_height="200dp" android:background="@drawable/layout_border" />
</LinearLayout>