티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
In Android, how do I set margins in dp programmatically?
안드로이드에서 코드로 dp단위로 마진을 어떻게 설정합니까?
문제 내용
In this, this and this thread I tried to find an answer on how to set the margins on a single view. However, I was wondering if there isn't an easier way. I'll explain why I rather wouldn't want to use this approach:
이것과 이 스레드에서 단일 보기에서 여백을 설정하는 방법에 대한 답변을 찾으려고 했습니다. 그러나 더 쉬운 방법이 없는지 궁금합니다. 이 접근 방식을 사용하고 싶지 않은 이유를 설명하겠습니다.
I have a custom Button which extends Button. If the background is set to something else than the default background (by calling either setBackgroundResource(int id)
or setBackgroundDrawable(Drawable d)
), I want the margins to be 0. If I call this:
Button을 상속한 커스텀 Button이 있습니다. 배경이 기본 배경이 아닌 다른 것으로 설정된 경우(setBackgroundResource(int id) 또는 setBackgroundDrawable(Drawable d)를 호출하여) 여백을 0으로 설정하고 싶습니다. 이렇게 호출하면 다음과 같습니다.
public void setBackgroundToDefault() {
backgroundIsDefault = true;
super.setBackgroundResource(android.R.drawable.btn_default);
// Set margins somehow
}
I want the margins to reset to -3dp (I already read here how to convert from pixels to dp, so once I know how to set margins in px, I can manage the conversion myself). But since this is called in the CustomButton
class, the parent can vary from LinearLayout to TableLayout, and I'd rather not have him get his parent and check the instanceof that parent. That'll also be quite inperformant, I imagine.
여백을 -3dp로 재설정하고 싶습니다(여기에서 픽셀에서 dp로 변환하는 방법을 이미 읽었으므로 여백을 px로 설정하는 방법을 알고 나면 직접 변환을 관리할 수 있습니다). 그러나 이것은 CustomButton 클래스에서 호출되기 때문에 부모는 LinearLayout에서 TableLayout까지 다양할 수 있으며, 그가 부모를 가져와서 해당 부모의 인스턴스를 확인하는 것을 원하지 않습니다. 그것은 또한 성능이 좋지 않을 것이라고 생각합니다.
Also, when calling (using LayoutParams) parentLayout.addView(myCustomButton, newParams)
, I don't know if this adds it to the correct position (haven't tried however), say the middle button of a row of five.
또한 (LayoutParams를 사용하여) parentLayout.addView(myCustomButton, newParams)를 호출할 때 이것이 올바른 위치에 추가되는지 모르겠습니다(그러나 시도하지는 않았습니다).
Question: Is there any easier way to set the margin of a single Button programmatically besides using LayoutParams?
질문: LayoutParams를 사용하는 것 외에 프로그래밍 방식으로 단일 버튼의 여백을 설정하는 더 쉬운 방법이 있습니까?
EDIT: I know of the LayoutParams way, but I'd like a solution that avoids handling each different container type:
편집: LayoutParams 방식을 알고 있지만 각기 다른 컨테이너 유형을 처리하지 않는 솔루션을 원합니다.
ViewGroup.LayoutParams p = this.getLayoutParams();
if (p instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)p;
if (_default) lp.setMargins(mc.oml, mc.omt, mc.omr, mc.omb);
else lp.setMargins(mc.ml, mc.mt, mc.mr, mc.mb);
this.setLayoutParams(lp);
}
else if (p instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)p;
if (_default) lp.setMargins(mc.oml, mc.omt, mc.omr, mc.omb);
else lp.setMargins(mc.ml, mc.mt, mc.mr, mc.mb);
this.setLayoutParams(lp);
}
else if (p instanceof TableRow.LayoutParams) {
TableRow.LayoutParams lp = (TableRow.LayoutParams)p;
if (_default) lp.setMargins(mc.oml, mc.omt, mc.omr, mc.omb);
else lp.setMargins(mc.ml, mc.mt, mc.mr, mc.mb);
this.setLayoutParams(lp);
}
}
Because this.getLayoutParams();
returns a ViewGroup.LayoutParams
, which do not have the attributes topMargin
, bottomMargin
, leftMargin
, rightMargin
. The mc instance you see is just a MarginContainer
which contains offset (-3dp) margins and (oml, omr, omt, omb) and the original margins (ml, mr, mt, mb).
this.getLayoutParams();는 topMargin, bottomMargin, leftMargin, rightMargin 속성이 없는 ViewGroup.LayoutParams를 반환하기 때문입니다. 표시되는 mc 인스턴스는 오프셋(-3dp) 여백과 (oml, omr, omt, omb) 및 원래 여백(ml, mr, mt, mb)을 포함하는 MarginContainer입니다.
높은 점수를 받은 Solution
You should use LayoutParams
to set your button margins:
LayoutParams(레이아웃 매개변수)를 사용하여 버튼 여백을 설정해야 합니다.
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
Depending on what layout you're using you should use RelativeLayout.LayoutParams
or LinearLayout.LayoutParams
.
사용 중인 레이아웃에 따라 RelativeLayout.LayoutParams 또는 LinearLayout.LayoutParams를 사용해야 합니다.
And to convert your dp measure to pixel, try this:
dp 측정값을 픽셀로 변환하려면 다음을 시도하십시오.
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics()
);
가장 최근 달린 Solution
Using Kotlin,
코틀린을 이용해서
yourLayoutId.updateLayoutParams<ViewGroup.MarginLayoutParams> {
setMargins(15,15,15,15)
}
출처 : https://stackoverflow.com/questions/12728255/in-android-how-do-i-set-margins-in-dp-programmatically
'개발 > 안드로이드' 카테고리의 다른 글
안드로이드에서 투명한 액티비티 만들기 (0) | 2022.12.14 |
---|---|
inflate 할 때 발생한 'Avoid passing null as the view root' 오류 수정하기 (0) | 2022.12.14 |
다른 패캐지의 디폴트 액티비티 실행하기 (0) | 2022.12.13 |
View의 GONE과 INVISIBLE의 차이 (0) | 2022.12.13 |
AlertDialog에서 표시되는 텍스트에 클릭 가능한 하이퍼링크 넣기 (0) | 2022.12.13 |