【问题标题】:Neither constructor nor onFinishInflate called for custom view构造函数和 onFinishInflate 都没有调用自定义视图
【发布时间】:2011-05-28 13:16:57
【问题描述】:

我有一个自定义视图(它扩展了 GLSurfaceView),我正尝试在我的应用中使用。使用它的 xml 布局似乎正在正确加载(应用了我为视图设置的属性),但是视图的构造函数和 onFinishInflate 方法都没有被调用。我还应该补充一点,我是 android 平台的新手,所以这可能是一个愚蠢的错误。

这是我的 main.xml

<?xml version="1.0" encoding="utf-8"?>

#<!-- Status Bar -->
<LinearLayout 
    android:orientation="horizontal"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:layout_weight="0"
    android:background="@drawable/status_bkg">

    #<!-- Location label -->
    <TextView 
        android:text="Location" 
        android:textColor="#FFFFFF"
        android:layout_weight="1" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    #<!-- Date/Time label -->
    <TextView 
        android:text="Date and Time" 
        android:textColor="#FFFFFF"
        android:layout_weight="1" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"  />
</LinearLayout>

#<!-- ChartView -->
<View class="com.xxx.yyy.ChartView" android:id="@+id/chartView"
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:background="#00FF00" 
    android:layout_weight="1">
</View>

ChartView 是自定义的 GLSurfaceView。此布局已加载,并且 ChartView 具有指定的绿色背景。但是,我的任何设置(在代码中)都没有发生。我尝试将它放在两个构造函数和 onFinishInflate 方法中,但莫名其妙地没有被调用。我已经验证了类名是正确的(xxx.yyy只是为了隐藏公司在这篇文章中。

我也尝试了不同形式的 xml 引用

    <com.xxx.yyy.ChartView android:id="@+id/chartView"
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:background="#00FF00" 
    android:layout_weight="1"/>

但是当加载 Activity 说构造函数时这个死了

ChartView(上下文上下文,AttributeSet attrs)

不存在(尽管它肯定在我的代码中)。

有人对可能发生的事情有任何提示吗?

【问题讨论】:

  • 粘贴视图的Java代码。

标签: android


【解决方案1】:

我终于想通了。我已将构造函数(未调用的构造函数)定义为:

public ChartView( MyActivity context, AttributeSet attrs )
{
    super( context, attrs );
….        
}

但是,当我将构造函数更改为:

public ChartView( Context context, AttributeSet attrs )
{
    super( context, attrs );
….        
}

鉴于 MyActivity 扩展了 Activity(它扩展了 Context),这是完全有效的代码,我相信它应该可以工作(它肯定可以编译)。系统在定位此方法时使用的反射似乎存在错误。

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多