【发布时间】:2015-08-26 21:08:47
【问题描述】:
我有一个扩展 TextView 的类,它基本上添加了一些羽毛来显示不同颜色的文本、动画等...
现在我正在使用其他不使用 Android TextView 但使用与 TextView 完全不相关的 Label 视图的自定义视图。
我想要做的是将所有逻辑和方法复制到一个新类中,该类将扩展 Label 并仅更改一些内容:颜色不是 int 类型而是 Color 类型等等。 setText(text) 的工作原理相同。
我是否必须真正复制粘贴所有课程并更改一些内容,或者我可以以某种方式使用一种逻辑并对新课程进行一些更改。当它扩展 Label 时,setText(text) 将在 Label 上执行相同的操作(Label 类也有该方法)
public class TextDisplayTextView extends TextView {
public TextDisplayTextView(Context context) {
super(context);
init();
}
public TextDisplayTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void setText (String text) {
// do some effects
setText(txt);
}
private void setTextColor (int color) {
// do some color effects
setTextColor(color);
}
.
.
.
}
新课程 - TextDisplayLabel
public class TextDisplayLabelView extends Label {
public TextDisplayLabelView(Label.Design design ) {
super(design);
init();
}
private void setText (String text) {
// do some effects
setText(txt);
}
private void setTextColor (Color color) {
// do some color effects
setLabelColor(color);
}
.
.
.
}
EDITED:我想在两种情况下使用它
在使用TextView 的类中:
TextDisplayTextView textV = (TextDisplayTextView) mLayout.findViewById(R.id.textDisplay);
mText.setText()
在课堂上使用Label:
Label.Design designStyle = new Label.Design designStyle();
TextDisplayLabelView textL = new TextDisplayTextView (designStyle);
textL.setText();
【问题讨论】:
-
也许使用抽象类和控制反转?您能否更具体地了解您要查找的内容?客户端代码如何使用每个类?
-
我正在使用这些类创建实例,并使用在那里实现的方法,例如
setColorWithA()、showTextAnimation()... 就像这样:mTextView.setColorWithA()或mLabelCustomView.setColorWithA() -
所以基本上,你有一个方法 setColorWithA() 根据它是 textView 还是 labelCustomView 设置特定的颜色?请提供一些您正在执行此操作的代码。什么最适合您的用例?抽象将取决于您如何使用这些类。正如 Sanjay Manohar 所注意到的,Java 中不存在多重继承,但是有一些策略可以解决此类问题,具体取决于您的需要。
-
@FrancisToth 我添加了代码来显示我应该使用它,基本上在使用
TextView的对象中使用第一个选项,而使用Label的对象使用第二个选项
标签: java android oop inheritance