我已经进行了很多研究,找到了很多解决此问题的资料,但是没有解决方案对我有用,我不知道怎么了。
我研究过的一些资源
https://androidpedia.net/en/tutorial/1446/creating-custom-views
https://infinum.com/the-capsized-eight/how-to-support-themes-in-custom-views-for-android-apps
这是此问题的仓库
https://github.com/burhankhanzada199888/CustomView-Style-StackOverflow-Question/tree/master/app
我的活动中有两个自定义视图,第一个没有样式标签,第二个有样式标签,但cardView样式仅在xml中使用时适用
activity_main.xml
<com.myapp.CustomCardView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <com.myapp.CustomCardView style="@style/CustomCardView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
CustomCardView.java
public class CustomCardView extends MaterialCardView { public CustomCardView(Context context) { this(context, null); } public CustomCardView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomCardView, defStyleAttr, R.style.CustomCardView); float imageSize = a.getDimension(R.styleable.CustomCardView_imageSize, 0); float textSize = a.getDimension(R.styleable.CustomCardView_textSize, 0); a.recycle(); inflate(context, R.layout.custom_view, this); ImageView imageView = findViewById(R.id.imageView); imageView.getLayoutParams().height = (int) imageSize; imageView.getLayoutParams().width = (int) imageSize; TextView textView = findViewById(R.id.textView); textView.setTextSize(textSize); }
}
styles.xml
<style name="CustomCardView" parent="Widget.MaterialComponents.CardView"> <item name="cardElevation">8dp</item> <item name="cardCornerRadius">16dp</item> <item name="android:layout_margin">8dp</item> <item name="cardBackgroundColor">?colorPrimary</item> <item name="imageSize">150dp</item> <item name="textSize">50sp</item> </style>
attrs.xml
<declare-styleable name="CustomCardView"> <attr name="imageSize" format="dimension|reference" /> <attr name="textSize" format="dimension|reference" /> </declare-styleable>
我已经进行了很多研究,找到了很多解决此问题的资料,但是没有解决方案对我有用,我不知道怎么了。我研究了一些自定义视图样式的资源,即android的...
这是因为您已经删除了public CustomCardView(Context context)
和public CustomCardView(Context context, AttributeSet attrs)
构造函数中的超级调用。确实,您的构造函数必须像这样: