【发布时间】:2017-04-04 14:26:16
【问题描述】:
我有 CustomLayout,它有 TextView,我在其上以编程方式设置文本和可绘制但问题是当我设置可绘制对象时,它添加了一个巨大的填充,而我想要绘制的内容更多地位于中心而不是顶部.
自定义视图组
public class ProfileGridView extends FrameLayout {
public ProfileGridView(@NonNull Context context) {
super(context);
initView(context,null);
}
public ProfileGridView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView(context,attrs);
}
public ProfileGridView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context,attrs);
}
@TargetApi(21)
public ProfileGridView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView(context,attrs);
}
public void initView(Context context, AttributeSet attrs) {
TextView gridTextView;
View view = inflate(context, R.layout.square_grid, null);
gridTextView = (TextView) view.findViewById(R.id.grid_description);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ProfileGridView);
Drawable drawable = array.getDrawable(R.styleable.ProfileGridView_drawble);
String description = array.getString(R.styleable.ProfileGridView_grid_description);
gridTextView.setText(description);
gridTextView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
addView(view);
array.recycle();
}
}
自定义视图布局文件
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawablePadding="8dp"
android:gravity="center"
android:padding="0dp"
android:textSize="20sp" />
MainActivit.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.views.ProfileGridView
android:layout_width="200dp"
android:layout_height="200dp"
app:drawble="@drawable/ic_message"
app:grid_description="Message"/>
</RelativeLayout>
【问题讨论】:
标签: android android-custom-view