以下代码假设是这样做的:
- 使用标准TextView显示字符串
- 使用扩展TextView显示字符串。 (这个覆盖了OnDraw并在字符串中画了一条线,使它看起来像被删除了)
问题是只出现了标准版本。
请检查以下代码:
package com.app.expensewatch;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Calendar;
public class ExpenseWatchActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int day,mon,yr;
Calendar cal = Calendar.getInstance();
day = cal.get(Calendar.DATE);
mon = 1 + cal.get(Calendar.MONTH);
yr = cal.get(Calendar.YEAR);
String text = getResources().getString(R.string.hello, day , mon , yr);
TextView tx1 = (TextView)findViewById(R.id.text1);
tx1.setText(text);
List1 list = (List1)findViewById(R.id.list1);
list.setText(text);
}
}
package com.app.expensewatch;
import android.util.AttributeSet;
import android.widget.TextView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.app.expensewatch.R;
public class List1 extends TextView {
public List1(Context context) {
super(context);
}
public List1(Context context, AttributeSet attrs) {
super( context, attrs );
}
public List1(Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
}
float ht = (float)getHeight();
float wd = (float)getWidth();
@Override
protected void onDraw(Canvas canvas)
{
Paint divider = new Paint();
divider.setColor(getResources().getColor(R.color.line1));
canvas.drawLine(0,ht/2,wd,ht/2,divider);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello" />
<com.app.expensewatch.List1
android:id="@+id/list1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello" />
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ExpenseWatch</string>
<string name="hello">Today is : %1$d / %2$d / %3$d</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="line1">#6456648f</color>
</resources>
答案 0 :(得分:1)
在扩展TextView中设置宽度和高度时,尚未测量视图。它的宽度和高度为零。在扩展的TextView中覆盖onMeasure(),并在那里设置宽度和高度。
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
ht = getHeight();
wd = getWidth();
}
在调用onMeasure()之后,始终避免设置将在视图中保存维度的私有变量。