只是尝试扩展 View 并做一些自定义工作,但是当我尝试覆盖 setFrame 方法时 Eclipse 会报错。声明父类中没有方法可以覆盖:
The method setFrame(int, int, int, int) of type Test must override or implement a supertype method
这里是来自android SDK源的方法签名。
protected boolean setFrame(int left, int top, int right, int bottom)
如您所见,它不是私有(private)或包级别,甚至没有指定为最终...只是 protected 。这应该意味着我完全能够在子类中覆盖它。正确的?下面是我在 Eclipse 中尝试做的最低限度的事情。也许这只是一个 Eclipse 错误,但我不太熟悉使用 Ant 来检查它。
编辑:对于那些回答说 setFrame 没有在 View 类中定义的人,我可以向你保证它是。您还认为我是如何获得方法签名的?它甚至在 layout() 期间被调用。还是我真的疯了?
git 头:View.java
纸杯蛋糕 (1.5r4):View.java
您甚至可以在 ImageView 中看到方法被覆盖和 TextView类...这就是为什么我不能直接从 View 自己覆盖它而感到非常困惑的原因...
public class Test extends View {
public Test(Context context) {
super(context);
}
public Test(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Test(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
return super.setFrame(left, top, right, bottom);
}
}
最佳答案
根据文档,setFrame
未在 View
类中定义(严格来说不正确 - 请参阅编辑)。令人惊讶的是,每个子类 TextView
和 ImageView
都是自己定义的。您必须为每个要覆盖此行为的小部件扩展特定的子类。这基于 Android 2.3 r1 - 2011 年 1 月 5 日 12:43
的文档。
查看文档:
定义setFrame的类
http://www.google.com/search?q=site:developer.android.com+%22boolean+setFrame%22
编辑:
正如 OP 在评论中指出的那样,该方法已在 View.java
源代码中明确定义。但是,文档就像没有在此处定义该方法一样。
这是因为 View
中的 setFrame() 方法有 @hide Javadoc 标签:
/**
* Assign a size and position to this view.
*
* This is called from layout.
*
* @param left Left position, relative to parent
* @param top Top position, relative to parent
* @param right Right position, relative to parent
* @param bottom Bottom position, relative to parent
* @return true if the new size and position are different than the
* previous ones
* {@hide}
*/
protected boolean setFrame(int left, int top, int right, int bottom) {
显然,这对 Javadoc 隐藏了方法:
http://www.androidjavadoc.com/?p=63
The especial [sic] attention is need to turn to the @hide tag which standard doclet can’t interpret and which hides non-SDK source and thus this code shouldn’t be used in applications.
它不能被覆盖的原因可能是 Android 的 Eclipse 插件或 Android 编译器以某种方式强制执行 @hide
标记?我不知道。
关于java - Android:为什么我不能从 View 中覆盖 setFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4751963/