【问题标题】:Why cast extended ImageView to ImageView?为什么要将扩展的 ImageView 转换为 ImageView?
【发布时间】:2011-06-12 15:09:24
【问题描述】:

我在一个名为 DialButton2 的类中扩展了 ImageView 类(不用担心类的名称,它无关紧要)。 DialButton2 类所做的只是显示位于可绘制文件夹中的任意图像。

package com.com.com;

import android.content.Context;
import android.widget.ImageView;
import android.util.AttributeSet;

public class DialButton2 extends ImageView{

    public DialButton2(Context context) {
        super(context);
        this.setImageResource(R.drawable.dialpad);
    }

    public DialButton2(Context context, AttributeSet attrs){
        super(context, attrs);
        this.setImageResource(R.drawable.dialpad);
    }

}

在我的应用程序的主要活动的 XML 文件中,我指定应显示 DialButton2 对象。我给它的 id 是“button1”。

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1"
    >
   <TableRow
    android:layout_weight="1">
         <DialButton
        android:id="@+id/button1"
        android:src="@drawable/dialpad"
        android:layout_weight="1"
        />

不要担心 XML 文件的其余部分,它们无关紧要。

我的问题是,当我尝试在代码中实例化对按钮的引用时,eclipse 告诉我必须将其转换为 ImageView。这是为什么呢?

package com.com.com;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

public class Android3 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.maintable);

        /*
         * The instantiating below gives an error saying I have to cast to ImageView.
         */

        DialButton2 button1 = findViewById(R.id.button1);
    }
}

【问题讨论】:

  • 如果没有 findViewById() 行,您的代码会编译并显示预期的视图吗?
  • XML 组件末尾缺少 2。此外,XML 组件前面没有完整的包名。不过问题解决了。

标签: android xml casting imageview extend


【解决方案1】:

您必须转换为 DialButton2

    DialButton2 button1 = (DialButton2) findViewById(R.id.button1);

findViewById() 返回一个视图,您必须先转换它才能将其用作 DialButton2。

【讨论】:

    【解决方案2】:

    您必须强制转换它,因为 getViewById(..) 返回一个 View 对象。当您从父类(View)转到子类(ImageView/DialButton2)时,需要进行强制转换。可以查看方法详情here

    【讨论】:

      【解决方案3】:

      您是否收到DialButton2 的天气无关紧要,因为无论您尝试使用findViewById(int)“查找”哪个视图,您都必须将其转换为正在初始化的同一类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-15
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        相关资源
        最近更新 更多