我需要一个具有纹理背景和动态文本的“按钮”。最终的结果应该是这样,但背景是一张质感的图片。 我试着用里面的
RelativeLayout
,但问题是CustomView
的结果不是wrap_content
的宽度/高度。带有自定义背景的Android TextView?
这里是custom_button
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@drawable/custom_button_selector"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
/>
</RelativeLayout>
这里是Code
:
public class CustomButton extends RelativeLayout {
private LayoutInflater mInflater;
private RelativeLayout mContainer;
private TextView mTextView;
public CustomButton(Context context) {
super(context);
mInflater = LayoutInflater.from(context);
customInit(context);
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
mInflater = LayoutInflater.from(context);
customInit(context);
}
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mInflater = LayoutInflater.from(context);
customInit(context);
}
private void customInit(Context ctx) {
mContainer = (RelativeLayout) mInflater.inflate(R.layout.cutom_button_view, this, true);
mTextView = (TextView) mContainer.findViewById(R.id.tv);
}
public RelativeLayout getContainer() {
return mContainer;
}
public TextView getTextView() {
return mTextView;
}
}
这是我如何使用它的那一刻,它工作:
<com.myapp.views.CustomButton
android:id="@+id/btn"
android:layout_width="80dp"
android:layout_height="50dp"/>
但我想使用这样的(动态文本),并将其将无法正常工作:
<com.myapp.views.CustomButton
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
实际上,它将在整个屏幕上伸展,无视布局规则。 如果这个解决方案是一个坏主意,你能推荐一个能产生相同结果的替代方案吗?
什么错'TextView.setBackground'? – pskink
它只是不会在图片上居中显示文字...我必须使用填充,但它会打破动态文本长度。其实,我的问题的核心是动态文本长度:( – nightfixed
什么是错误的'TextView.setGravity'? – pskink