我在我EditText
和Button
视图上有这个问题,我有一个很好的填充,让他们远离文本,但当我改变背景setBackgroundDrawable
或setBackgroundResource
填充永远丢失.
Mat*_*inn 95
我发现添加一个9补丁作为后台资源重置填充 - 虽然有趣的是,如果我添加了一个颜色,或非9补丁图像,它没有.解决方案是在添加背景之前保存填充值,然后再次设置它们.
private EditText value = (EditText) findViewById(R.id.value);
int pL = value.getPaddingLeft();
int pT = value.getPaddingTop();
int pR = value.getPaddingRight();
int pB = value.getPaddingBottom();
value.setBackgroundResource(R.drawable.bkg);
value.setPadding(pL, pT, pR, pB);
Run Code Online (Sandbox Code Playgroud)
The*_*ist 13
我能够将元素包装在另一个布局中,在本例中为a FrameLayout
.这使我能够在FrameLayout
不破坏填充的情况下更改背景RelativeLayout
.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/commentCell"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/comment_cell_bg_single" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="20dp" >
<ImageView android:id="@+id/sourcePic"
android:layout_height="75dp"
android:layout_width="75dp"
android:padding="5dp"
android:background="@drawable/photoframe"
/>
...
Run Code Online (Sandbox Code Playgroud)
另一个选项是在设置背景后以编程方式设置它Drawable
,如上所述.只需确保计算像素以校正设备的分辨率.
Luk*_*ner 11
我在TextView中遇到了这个问题,所以我将TextView子类化并制作了方法的Override TextView.setBackgroundResource(int resid)
方法.像这样:
@Override
public void setBackgroundResource(int resid) {
int pl = getPaddingLeft();
int pt = getPaddingTop();
int pr = getPaddingRight();
int pb = getPaddingBottom();
super.setBackgroundResource(resid);
this.setPadding(pl, pt, pr, pb);
}
Run Code Online (Sandbox Code Playgroud)
这样,它在设置资源之前获取项目的填充,但实际上并没有弄乱方法的原始功能,除了保持填充.
没有彻底测试这个超级,但这种方法可能有用:
/**
* Sets the background for a view while preserving its current padding. If the background drawable
* has its own padding, that padding will be added to the current padding.
*
* @param view View to receive the new background.
* @param backgroundDrawable Drawable to set as new background.
*/
public static void setBackgroundAndKeepPadding(View view, Drawable backgroundDrawable) {
Rect drawablePadding = new Rect();
backgroundDrawable.getPadding(drawablePadding);
int top = view.getPaddingTop() + drawablePadding.top;
int left = view.getPaddingLeft() + drawablePadding.left;
int right = view.getPaddingRight() + drawablePadding.right;
int bottom = view.getPaddingBottom() + drawablePadding.bottom;
view.setBackgroundDrawable(backgroundDrawable);
view.setPadding(left, top, right, bottom);
}
Run Code Online (Sandbox Code Playgroud)
使用它代替view.setBackgroundDrawable(Drawable).
您可以通过使用 9 块图像并在可绘制对象中定义内容区域来提供一些填充。 检查这个
您还可以通过 xml 或以编程方式设置布局中的填充
xml 填充标签
android:padding
android:paddingLeft
android:paddingRight
android:paddingTop
android:paddingBottom
Run Code Online (Sandbox Code Playgroud)
在调用 setBackgroundDrawable 后,您可以尝试通过在 EditText 或按钮视图上调用 setPadding 来手动设置填充
归档时间: |
|
查看次数: |
25601 次 |
最近记录: |