Android学习笔记技巧之给文本加边框-LMLPHP

BorderTextViews.Java

  1. package xiaosi.BorderTextView;
  2. import android.content.Context;
  3. import android.graphics.Canvas;
  4. import android.graphics.Color;
  5. import android.graphics.Paint;
  6. import android.util.AttributeSet;
  7. import android.widget.TextView;
  8. public class BorderTextViews extends TextView
  9. {
  10. private Paint paint = null;
  11. private int color = Color.GRAY;
  12. public BorderTextViews(Context context, AttributeSet attrs)
  13. {
  14. super(context, attrs);
  15. }
  16. //设置边框颜色
  17. public void setPaintColor(int color){
  18. this.color = color;
  19. }
  20. @Override
  21. protected void onDraw(Canvas canvas)
  22. {
  23. super.onDraw(canvas);
  24. paint = new Paint();
  25. //给边框设置颜色
  26. paint.setColor(color);
  27. //上
  28. canvas.drawLine(0, 0, this.getWidth()-1, 0, paint);
  29. //左
  30. canvas.drawLine(0, 0, 0, this.getHeight()-1, paint);
  31. //下
  32. canvas.drawLine(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1, paint);
  33. //右
  34. canvas.drawLine(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1, paint);
  35. }
  36. }
  1. package xiaosi.BorderTextView;
  2. import android.app.Activity;
  3. import android.graphics.Color;
  4. import android.os.Bundle;
  5. public class BorderTextViewActivity extends Activity {
  6. /** Called when the activity is first created. */
  7. private BorderTextViews borderTextView = null;
  8. @Override
  9. public void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.main);
  12. borderTextView = (BorderTextViews)findViewById(R.id.Border);
  13. borderTextView.setPaintColor(Color.GRAY);
  14. }
  15. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical"
  6. android:background="#CCFF66">
  7. <xiaosi.BorderTextView.BorderTextViews
  8. android:id="@+id/Border"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:textColor="#C71585"
  12. android:layout_marginTop="20dp"
  13. android:padding="10dp"
  14. android:layout_gravity="center"
  15. android:text="在画布上画边框" />
  16. </LinearLayout>
05-18 01:02