1
以下代碼假設要這樣做:
- 使用標準TextView顯示字符串
- 使用擴展TextView顯示字符串。 (這個覆蓋了OnDraw並在字符串上畫了一條線,使其看起來像被刪除了)擴展TextView不出現
問題是隻有標準顯示。
請檢查下面的代碼:
ExpenseWatchActivity.java(這是主要的活性)
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);
}
}
List1.java(這是擴展的TextView)
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
<?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>
的strings.xml
<?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>
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="line1">#6456648f</color>
</resources>
好的,非常感謝。根據你的建議,我得到了一條線,但是,文本丟失了...所以基本上,我得到的只是線... – user1455536
如果你想要通常在那裏顯示的文本,請調用超類的onDraw在你的方法中。如果您希望繪製在文本頂部顯示的內容,請將超級調用放在方法的開頭,如果希望顯示在文本下方,請將超級調用放在方法的底部。該調用看起來像super.onDraw(canvas)。行! – Flynn81
行!一切正常!非常感謝! – user1455536