Android 텍스트 뷰 주위에 테두리를 어떻게 두나요?
텍스트 뷰 주위에 테두리를 그릴 수 있습니까?
모양 드로어 블 (사각형)을 뷰의 배경으로 설정할 수 있습니다.
<TextView android:text="Some text" android:background="@drawable/back"/>
그리고 직사각형 drawable back.xml (res / drawable 폴더에 넣음) :
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/white" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
@android:color/transparent
단색을 사용 하여 배경을 투명하게 만들 수 있습니다 . 패딩을 사용하여 테두리에서 텍스트를 분리 할 수도 있습니다. 자세한 내용은 http://developer.android.com/guide/topics/resources/drawable-resource.html을 참조하십시오.
몇 가지 다른 (비프로 그래 매틱) 방법을 요약하겠습니다.
도형 드로어 블 사용
드로어 블 폴더 (예 : my_border.xml)에 다음을 XML 파일로 저장합니다.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- View background color -->
<solid
android:color="@color/background_color" >
</solid>
<!-- View border color and width -->
<stroke
android:width="1dp"
android:color="@color/border_color" >
</stroke>
<!-- The radius makes the corners rounded -->
<corners
android:radius="2dp" >
</corners>
</shape>
그런 다음 TextView의 배경으로 설정하십시오.
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_border" />
추가 도움말 :
9 패치 사용
9 패치는 확장 가능한 배경 이미지입니다. 테두리가있는 이미지를 만들면 TextView에 테두리가 제공됩니다. 필요한 것은 이미지를 만든 다음 TextView의 배경으로 설정하는 것입니다.
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_ninepatch_image" />
다음은 9 패치 이미지를 만드는 방법을 보여주는 몇 가지 링크입니다.
상단 테두리 만 원하면 어떻게하나요?
레이어 목록 사용
레이어 목록을 사용하여 두 개의 직사각형을 서로 쌓을 수 있습니다. 두 번째 사각형을 첫 번째 사각형보다 약간 작게 만들어 테두리 효과를 만들 수 있습니다. 첫 번째 (아래쪽) 사각형은 테두리 색상이고 두 번째 사각형은 배경색입니다.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Lower rectangle (border color) -->
<item>
<shape android:shape="rectangle">
<solid android:color="@color/border_color" />
</shape>
</item>
<!-- Upper rectangle (background color) -->
<item android:top="2dp">
<shape android:shape="rectangle">
<solid android:color="@color/background_color" />
</shape>
</item>
</layer-list>
설정 android:top="2dp"
은 상단을 2dp만큼 오프셋합니다 (더 작게 만듭니다). 이렇게하면 첫 번째 (아래쪽) 사각형이 표시되어 테두리 효과가 나타납니다. shape
위에서 드로어 블이 수행 된 것과 동일한 방식으로 TextView 배경에이를 적용 할 수 있습니다 .
다음은 레이어 목록에 대한 추가 링크입니다.
- 안드로이드 <레이어리스트> 이해하기
- 드로어 블 모양 XML 선택기에서 아래쪽 테두리를 만드는 방법은 무엇입니까?
- 3면에 드로어 블 XML의 Android 뷰에 테두리를 만드시겠습니까?
9 패치 사용
하나의 테두리로 9 패치 이미지를 만들 수 있습니다. 다른 모든 것은 위에서 설명한 것과 동일합니다.
보기 사용
이것은 일종의 트릭이지만 두보기 사이에 구분 기호를 추가하거나 단일 TextView에 테두리를 추가해야하는 경우 잘 작동합니다.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- This adds a border between the TextViews -->
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@android:color/black" />
<TextView
android:id="@+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
다음은 몇 가지 추가 링크입니다.
간단한 방법은 TextView에 대한보기를 추가하는 것입니다. 하단 경계선의 예 :
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:text="@string/title"
android:id="@+id/title_label"
android:gravity="center_vertical"/>
<View
android:layout_width="fill_parent"
android:layout_height="0.2dp"
android:id="@+id/separator"
android:visibility="visible"
android:background="@android:color/darker_gray"/>
</LinearLayout>
다른 방향 테두리의 경우 구분선보기의 위치를 조정하십시오.
textview를 확장하고 테두리를 수동으로 그려서이 문제를 해결했습니다. 테두리가 점선인지 파선인지 선택할 수 있도록 추가했습니다.
public class BorderedTextView extends TextView {
private Paint paint = new Paint();
public static final int BORDER_TOP = 0x00000001;
public static final int BORDER_RIGHT = 0x00000002;
public static final int BORDER_BOTTOM = 0x00000004;
public static final int BORDER_LEFT = 0x00000008;
private Border[] borders;
public BorderedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public BorderedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BorderedTextView(Context context) {
super(context);
init();
}
private void init(){
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(4);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(borders == null) return;
for(Border border : borders){
paint.setColor(border.getColor());
paint.setStrokeWidth(border.getWidth());
if(border.getStyle() == BORDER_TOP){
canvas.drawLine(0, 0, getWidth(), 0, paint);
} else
if(border.getStyle() == BORDER_RIGHT){
canvas.drawLine(getWidth(), 0, getWidth(), getHeight(), paint);
} else
if(border.getStyle() == BORDER_BOTTOM){
canvas.drawLine(0, getHeight(), getWidth(), getHeight(), paint);
} else
if(border.getStyle() == BORDER_LEFT){
canvas.drawLine(0, 0, 0, getHeight(), paint);
}
}
}
public Border[] getBorders() {
return borders;
}
public void setBorders(Border[] borders) {
this.borders = borders;
}
}
그리고 국경 클래스 :
public class Border {
private int orientation;
private int width;
private int color = Color.BLACK;
private int style;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public int getStyle() {
return style;
}
public void setStyle(int style) {
this.style = style;
}
public int getOrientation() {
return orientation;
}
public void setOrientation(int orientation) {
this.orientation = orientation;
}
public Border(int Style) {
this.style = Style;
}
}
이것이 누군가를 돕기를 바랍니다 :)
나는 비슷한 대답을 보았습니다 .Stroke와 다음 재정의로 수행 할 수 있습니다.
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Paint strokePaint = new Paint();
strokePaint.setARGB(255, 0, 0, 0);
strokePaint.setTextAlign(Paint.Align.CENTER);
strokePaint.setTextSize(16);
strokePaint.setTypeface(Typeface.DEFAULT_BOLD);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Paint textPaint = new Paint();
textPaint.setARGB(255, 255, 255, 255);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(16);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
canvas.drawText("Some Text", 100, 100, strokePaint);
canvas.drawText("Some Text", 100, 100, textPaint);
super.draw(canvas, mapView, shadow);
}
두 가지 방법으로 테두리를 설정할 수 있습니다. 하나는 드로어 블에 의한 것이고 두 번째는 프로그래밍 방식입니다.
드로어 블 사용
<shape>
<solid android:color="@color/txt_white"/>
<stroke android:width="1dip" android:color="@color/border_gray"/>
<corners android:bottomLeftRadius="10dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="10dp"
android:topRightRadius="0dp"/>
<padding android:bottom="0dip"
android:left="0dip"
android:right="0dip"
android:top="0dip"/>
</shape>
프로그래밍 방식
public static GradientDrawable backgroundWithoutBorder(int color) {
GradientDrawable gdDefault = new GradientDrawable();
gdDefault.setColor(color);
gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
radius, radius });
return gdDefault;
}
내가 찾은 (실제로 작동하는) 가장 간단한 솔루션 :
<TextView
...
android:background="@android:drawable/editbox_background" />
TextView 주위에 테두리를 두는 더 좋은 방법을 찾았습니다.
배경에는 나인 패치 이미지를 사용하십시오. 매우 간단합니다. SDK에는 9 패치 이미지를 만드는 도구가 포함되어 있으며 코딩 이 전혀 필요하지 않습니다 .
링크는 http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch 입니다.
코드에 다음과 같이 추가 할 수 있습니다.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ffffff" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
둥근 모서리를 만들려면 아래 링크를 확인하십시오. http://androidcookbook.com/Recipe.seam?recipeId=2318
Android 프로젝트의 res 아래에있는 드로어 블 폴더는 비트 맵 (PNG 또는 JPG 파일)으로 제한되지 않지만 XML 파일에 정의 된 모양을 저장할 수도 있습니다.
그런 다음 이러한 모양을 프로젝트에서 재사용 할 수 있습니다. 모양을 사용하여 레이아웃 주위에 테두리를 둘 수 있습니다. 이 예는 모서리가 구부러진 직사각형 테두리를 보여줍니다. customborder.xml이라는 새 파일이 드로어 블 폴더에 생성됩니다 (Eclipse에서는 파일 메뉴를 사용하고 새로 만들기를 선택한 다음 파일을 선택하고 파일 이름에 드로어 블 폴더 유형을 선택하고 마침을 클릭합니다).
테두리 모양을 정의하는 XML이 입력됩니다.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="20dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#CCCCCC"/>
</shape>
속성 android:shape
은 직사각형으로 설정됩니다 (모양 파일은 타원형, 선 및 링도 지원함). Rectangle이 기본값이므로 정의되는 사각형 인 경우이 속성을 생략 할 수 있습니다. 모양 파일에 대한 자세한 내용 은 http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape 에서 모양에 대한 Android 설명서를 참조하십시오 .
요소 모서리는 사각형 모서리를 둥글게 설정합니다. 각 모서리에 다른 반경을 설정할 수 있습니다 (Android 참조 참조).
padding 속성은 내용이 테두리와 겹치는 것을 방지하기 위해 모양이 적용된 View의 내용을 이동하는 데 사용됩니다.
여기서 테두리 색상은 밝은 회색 (CCCCCC 16 진수 RGB 값)으로 설정됩니다.
모양도 그라디언트를 지원하지만 여기에서는 사용되지 않습니다. 다시 말하지만, 그라디언트가 어떻게 정의되는지 보려면 Android 리소스를 참조하십시오. 모양은를 사용하여 레이아웃에 적용됩니다 android:background="@drawable/customborder"
.
레이아웃 내에서 다른보기를 정상적으로 추가 할 수 있습니다. 이 예에서는 단일 TextView가 추가되었으며 텍스트는 흰색 (FFFFFF 16 진수 RGB)입니다. 배경은 파란색으로 설정되고 밝기를 줄이기 위해 약간의 투명도를 더합니다 (A00000FF 16 진수 알파 RGB 값). 마지막으로 레이아웃은 약간의 패딩으로 다른 레이아웃에 배치하여 화면 가장자리에서 오프셋됩니다. 따라서 전체 레이아웃 파일은 다음과 같습니다.
<?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:padding="5dp">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/customborder">
<TextView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Text View"
android:textSize="20dp"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"
android:background="#A00000FF" />
</LinearLayout>
</LinearLayout>
아주 간단하게 할 수있는 방법이 있고 공유하고 싶습니다.
TextViews를 제곱하고 싶을 때 LinearLayout에 넣습니다. LinearLayout의 배경색을 설정하고 TextView에 여백을 추가합니다. 결과는 TextView를 제곱하는 것과 같습니다.
다음은 테두리가있는 ImageView를 반환하는 '간단한'도우미 클래스입니다. 이것을 utils 폴더에 놓고 다음과 같이 호출하십시오.
ImageView selectionBorder = BorderDrawer.generateBorderImageView(context, borderWidth, borderHeight, thickness, Color.Blue);
다음은 코드입니다.
/**
* Because creating a border is Rocket Science in Android.
*/
public class BorderDrawer
{
public static ImageView generateBorderImageView(Context context, int borderWidth, int borderHeight, int borderThickness, int color)
{
ImageView mask = new ImageView(context);
// Create the square to serve as the mask
Bitmap squareMask = Bitmap.createBitmap(borderWidth - (borderThickness*2), borderHeight - (borderThickness*2), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(squareMask);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
canvas.drawRect(0.0f, 0.0f, (float)borderWidth, (float)borderHeight, paint);
// Create the darkness bitmap
Bitmap solidColor = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(solidColor);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
canvas.drawRect(0.0f, 0.0f, borderWidth, borderHeight, paint);
// Create the masked version of the darknessView
Bitmap borderBitmap = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(borderBitmap);
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawBitmap(solidColor, 0, 0, null);
canvas.drawBitmap(squareMask, borderThickness, borderThickness, clearPaint);
clearPaint.setXfermode(null);
ImageView borderView = new ImageView(context);
borderView.setImageBitmap(borderBitmap);
return borderView;
}
}
내 경우에는 작동하지 않기 때문에 Konstantin Burov 대답을 변경하십시오.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<stroke android:width="2dip" android:color="#4fa5d5"/>
<corners android:radius="7dp"/>
</shape>
</item>
</selector>
compileSdkVersion 26 (Android 8.0), minSdkVersion 21 (Android 5.0), targetSdkVersion 26, 구현 'com.android.support:appcompat-v7:26.1.0', gradle : 4.1
이것은 당신을 도울 수 있습니다.
<RelativeLayout
android:id="@+id/textbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@android:color/darker_gray" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="3dp"
android:background="@android:color/white"
android:gravity="center"
android:text="@string/app_name"
android:textSize="20dp" />
</RelativeLayout
배경색을 테두리 색상과 텍스트보기 크기로 사용하여 테두리보기를 만듭니다. 테두리보기 패딩을 테두리 너비로 설정합니다. 텍스트보기에 대해 원하는 색상으로 텍스트보기 배경색을 설정하십시오. 이제 테두리보기 안에 텍스트보기를 추가하십시오.
이 시도:
<shape>
<solid android:color="@color/txt_white"/>
<stroke android:width="1dip" android:color="@color/border_black"/>
</shape>
textView에 테두리를 추가하는 방법에는 여러 가지가 있습니다. 가장 간단한 방법은 사용자 정의 드로어 블을 만들고이를 android:background="@drawable/textview_bg"
textView 로 설정하는 것 입니다.
textview_bg.xml은 Drawables 아래에 있으며 다음과 같을 수 있습니다. 당신은 할 수 있습니다 solid
또는 gradient
(필요하지 않은 경우 또는 아무것도), 배경 corners
코너 반경을 추가하고 stroke
테두리를 추가 할 수 있습니다.
textview_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="@dimen/dp_10"/>
<gradient
android:angle="225"
android:endColor="#FFFFFF"
android:startColor="#E0E0E0" />
<stroke
android:width="2dp"
android:color="#000000"/>
</shape>
텍스트보기에 대한 사용자 지정 배경을 만들 수 있습니다. 단계 1. 프로젝트로 이동합니다. 2. 리소스로 이동하여 드로어 블을 마우스 오른쪽 버튼으로 클릭합니다. 3. New-> Drawable Resource File을 클릭합니다. 4. 파일 이름을 지정합니다. 5. 파일에 다음 코드를 붙여 넣습니다.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="@color/colorBlack" />
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" />
<corners android:radius="6dp" />
<solid android:color="#ffffffff" />
배경으로 사용하려는 텍스트보기의 경우
android : background = "@ drawable / your_fileName"
사실 아주 간단합니다. Textview 뒤에 간단한 검은 색 사각형을 원하면 android:background="@android:color/black"
TextView 태그 내에 추가하기 만하면 됩니다. 이렇게 :
<TextView
android:textSize="15pt" android:textColor="#ffa7ff04"
android:layout_alignBottom="@+id/webView1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="@android:color/black"/>
참고 URL : https://stackoverflow.com/questions/3496269/how-do-i-put-a-border-around-an-android-textview
'code' 카테고리의 다른 글
JavaScript에서 클래스를 정의하는 데 사용할 수있는 기술은 무엇이며 그 장단점은 무엇입니까? (0) | 2020.09.30 |
---|---|
C #에서 string.Empty 또는 String.Empty 또는 ""를 사용하여 문자열을 초기화해야합니까? (0) | 2020.09.30 |
레이아웃의 Android 드로잉 구분선 / 분할 선? (0) | 2020.09.30 |
Android에서 프로그래밍 방식으로 현재 GPS 위치를 얻는 방법은 무엇입니까? (0) | 2020.09.30 |
Bash 스크립트의 파일에 heredoc을 어떻게 작성할 수 있습니까? (0) | 2020.09.30 |