【发布时间】:2017-10-28 08:24:19
【问题描述】:
我有一种情况,我想调试对TextView.onDraw() 的调用,所以我将其子类化如下:
public class MyTextView extends AppCompatTextView {
View parent;
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void storeParent(View parent) {
this.parent = parent;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
并将其放在这样的层次结构中:(参见MyTextView)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.scrollviewtest1.MainActivity">
<LinearLayout
android:id="@+id/scroll_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.scrollviewtest1.MyTextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/large_text" />
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
</ScrollView>
最后,我为这个TextView 放了一大段文字,这样它就可以滚动了。
现在,如果我在 onDraw() 方法中放置一个断点,我只会得到一个调用。根据我的理解,当我向上和向下滚动时,我应该会接到它的电话。为什么会这样?
旁注:我已经尝试设置setWillNotDraw(false),结果没有变化。
【问题讨论】:
-
通常情况下,您不应该对
onDraw()方法的调用次数做出假设。为什么需要调用它? -
@azizbekian :用于测试目的;不生产
-
@azizbekian :但是,当您向上或向下滚动时,它应该在逻辑上被调用
-
你可以使用
text2.invalidate();。 -
But, it should get called logically, when you scroll up or down同意,我也希望onDraw()被调用,但可能是因为该视图在ScrollView内部,而您只需执行滚动,那么只有TextView的DisplayList是正在更新,导致优化不调用每个孩子的onDraw()方法,这个我不确定。
标签: java android textview android-custom-view