【问题标题】:Overriding an Android View E.g. MyHeading : TextView覆盖 Android 视图,例如我的标题:文本视图
【发布时间】:2017-12-23 10:37:10
【问题描述】:

帮助!在 VS2017 上使用 Xamarin,我正在努力实现这一目标:

我可以在任何地方使用的 MyHeading 类,就像普通的 TextView 类一样,除了任何 MyHeading 实例都将继承我仅为 MyHeading 定义的填充/边距/样式/字体等。

我迷路了,运气不好,在 Google 上找不到任何有用的东西。

我创建了继承自 TextView 的 MyHeading.cs:

public class MyHeading : TextView
{
    public MyHeading(Context context) : base(context)
    {

    }
}

然后我还在包含此 XML 的 Resources/layout 文件夹中创建了 myheading.xml:

<?xml version="1.0" encoding="utf-8"?>
<com.my.app.MyHeading    
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/mygrey"
android:textSize="18dp"
android:textStyle="bold"
android:typeface="sans"
android:gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp" />

请帮忙!我怎样才能实现这样一个简单的要求,即在我使用它时拥有一个具有相同样式的可重复使用的 TextView。

使用我上面的代码,项目成功构建,但是当我运行它时,它会出现以下问题:

Java.Lang.NoClassDefFoundError: android.support.v7.appcompat.R$drawable

【问题讨论】:

  • 我建议宁愿使用 Android style xml attribute,它是共享通用样式的更常见模式。至于您遇到的问题,我相信您需要添加缺少的构造函数重载并夸大您的自定义布局。

标签: android inheritance xamarin xamarin.android


【解决方案1】:

正如 cmets 建议的那样(我也建议),在 Android 上创建 style 比创建 View 子类更合适,也是更常见的模式。

示例

资源/值/styles.xml

<?xml version="1.0" encoding="UTF-8" ?>
<resources>
    <style name="MyHeadingStyle" parent="android:Widget.TextView">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@color/red</item>
        <item name="android:textSize">18dp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:typeface">sans</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_marginTop">20dp</item>
        <item name="android:layout_marginBottom">10dp</item> 
    </style>
    ~~~ other styles ~~~
</resources>

AXML 示例:

<TextView
    android:text="StackOverFlow"
    style="@style/MyHeadingStyle" />

输出:

回复:Android Styles and Themes

【讨论】:

  • 非常感谢这个 SushiHangover。我直接跳过了这个,但是很高兴看到 Android 以与 CSS 等类似的方式支持样式。它现在对我有用,干杯。
  • @Aaron 没问题,很高兴它有帮助。当我编辑这些样式和主题时,我总是希望有一个视觉继承/树样式编辑器......也许谷歌会在那一年做点什么,哈哈......?
  • 嘿寿司,想知道你是否可以在这里帮助我解决我的其他问题? stackoverflow.com/questions/47958241/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 2014-10-20
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多