LinearLayout에 테두리 그리기
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Android: how to draw a border to a LinearLayout
Android: LinearLayout에 테두리를 그리는 방법
문제 내용
I have three files. The XML, the draw function and the main Activity. I have some LinearLayout
in my XML file.
저는 세 개(XML, 그리기 기능 및 메인 액티비티)의 파일이 있습니다. XML 파일에 LinearLayout이 있습니다.
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#ef3"
android:id="@+id/img01"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#E8A2B4"
android:id="@+id/img02"/>
</LinearLayout>
This is the draw function:
그리기 기능은 다음과 같습니다.
public class getBorder extends TextView {
public getBorder(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(android.graphics.Color.RED);
canvas.drawLine(0, 0, this.getWidth() - 1, 0, paint);
canvas.drawLine(0, 0, 0, this.getHeight() - 1, paint);
canvas.drawLine(this.getWidth() - 1, 0, this.getWidth() - 1,
this.getHeight() - 1, paint);
canvas.drawLine(0, this.getHeight() - 1, this.getWidth() - 1,
this.getHeight() - 1, paint);
}
}
And this is the main Activity:
메인 액티비티는 다음과 같습니다.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final getBorder getBorder = new getBorder(this);
final LinearLayout img01 = (LinearLayout) findViewById(R.id.img01);
img01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getBorder.setWidth(100);
getBorder.setHeight(100);
img01.addView(getBorder);
}
});
}
The program could draw border but the size doesn't fit the LinearLayout
. And when I click the LinearLayout
again, the program crashed.
프로그램에서 테두리를 그릴 수 있지만 크기가 LinearLayout에 맞지 않습니다. 그리고 LinearLayout을 다시 클릭했을 때 프로그램이 충돌했습니다.
Also, I want to draw two circles in the center of the LinearLayout
, but how could I figure out the center coordinates?
또한, LinearLayout의 중심에 원을 두 개 그리고 싶은데, 중심 좌표를 어떻게 알 수 있을까요?
높은 점수를 받은 Solution
Do you really need to do that programmatically?
정말 프로그래밍 방식으로 그렇게 할 필요가 있습니까?
Just considering the title: You could use a ShapeDrawable as android:background…
제목만 생각하면: ShapeDrawable을 Android:background로 사용할 수 있습니다.
For example, let's define res/drawable/my_custom_background.xml
as:
예를 들어 res/drawable/my_custom_background.xml을 다음과 같이 정의합니다.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp" />
<stroke
android:width="1dp"
android:color="@android:color/white" />
</shape>
and define android:background="@drawable/my_custom_background".
android:background="@drawable/my_custom_background"를 정의합니다.
I've not tested but it should work.
저는 테스트를 하지 않았지만 그것은 효과가 있을 거에요.
Update:
업데이트:
I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml
당신의 필요에 맞는 경우 xml shapre drawable 리소스 기능을 활용하는 것이 더 낫다고 생각합니다. "처음부터" 프로젝트(android-8용)로 res/layout/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="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border"
android:padding="10dip" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
[... more TextView ...]
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
</LinearLayout>
and a res/drawable/border.xml
및 ares/drawable/border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dip"
android:color="@android:color/white" />
</shape>
Reported to work on a gingerbread device. Note that you'll need to relate android:padding
of the LinearLayout to the android:width
shape/stroke's value. Please, do not use @android:color/white
in your final application but rather a project defined color.
진저브레드 디바이스에서 작업하는 것으로 보고되었습니다. LinearLayout의 android:padding을 android:width shape/stroke의 값과 연결해야 합니다. 최종 애플리케이션에서 @android:color/white를 사용하지 말고 프로젝트 정의 색상을 사용하세요.
You could apply android:background="@drawable/border" android:padding="10dip"
to each of the LinearLayout from your provided sample.
제공된 샘플의 각 LinearLayout에 android:background="@drawable/border" android:padding="10dip" 를 적용할 수 있습니다.
As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…
일부 원을 LinearLayout의 배경으로 표시하는 것과 관련된 다른 게시물에 관해서는 LinearLayout의 배경에 완벽한 원을 표시하기 위해 작동하는 무언가를 얻기 위해 Inset/Scale/Layer 드로어블 리소스(자세한 내용은 드로어블 리소스 참조)를 사용하고 있지만 실패했습니다. 현재…
Your problem resides clearly in the use of getBorder.set{Width,Height}(100);
. Why do you do that in an onClick method?
당신의 문제는 getBorder.set{Width,Height}(100); 사용에 분명히 있습니다. 왜 onClick 메서드에서 그렇게 하나요?
I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.
요점을 놓치지 않으려면 추가 정보가 필요합니다. 프로그래밍 방식으로 수행하는 이유는 무엇입니까? 동적 동작이 필요합니까? 입력 drawable에 png 또는 ShapeDrawable이 허용되나요? 등..
To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…
계속 될거에요(아마도 내일 그리고 달성하고자 하는 목표에 대해 더 정확한 정보를 제공하는 즉시)…
가장 최근 달린 Solution
Extend LinearLayout/RelativeLayout and use it straight on the XML
LinearLayout/RelativeLayout을 상속하여 XML에서 직접 사용
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
출처 : https://stackoverflow.com/questions/8203606/android-how-to-draw-a-border-to-a-linearlayout