安卓开发入门之自定义View(翻译)

来源:互联网 发布:js获取访问者ip地址 编辑:程序博客网 时间:2024/06/05 11:16
文章链接
https://www.tutorialspoint.com/android/android_custom_components.htm

安卓里面提供了大量的基础控件(View),如Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView等。我们可以在安卓应用开发中直接使用它们,但是有些时候它们并不能满足我们的要求,比如TextView显示文本时过滤掉null值。幸运的是,安卓提供我们自定义View用来满足我们的定制需求。

假如我们仅仅需要对已存在的View做微调,我们只需继承该View并且通过重写其中的方法来精确控制显示效果。

本文将通过简单且容易理解的方式介绍如何创建自定义View并且在开发中使用。


创建一个简单的自定义View步骤如下:
1.创建名为myapplication 的工程。
2.在res/values/attrs.xml创建新的属性。
3.创建MainActivity
4.在activity_main.xml中添加自定义的View。
5.运行。

attrs.xml文件内容如下:

<?xml version="1.0" encoding="utf-8"?><resources>      <declare-styleable name="TimeView">         <attr name="title" format="string" />         <attr name="setColor" format="boolean"/>   </declare-styleable></resources>


activity_main.xml文件内容如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"   xmlns:custom="http://schemas.android.com/apk/res-auto"   android:layout_width="match_parent"   android:layout_height="match_parent"   tools:context=".MainActivity" >   <com.example.tutorialspoint7.myapplication.TimeView      android:id="@+id/timeView"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:textColor="#fff"      android:textSize="40sp"      custom:title="my time view"      custom:setColor="true" />   <TextView      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:id="@+id/simple"      android:layout_below="@id/timeView"      android:layout_marginTop="10dp" /></RelativeLayout>



TimeView.java文件

public class TimeView extends TextView {   private String titleText;   private boolean color;   public TimeView(Context context) {      super(context);      setTimeView();   }   public TimeView(Context context, AttributeSet attrs) {      super(context, attrs);      // retrieved values correspond to the positions of the attributes         TypedArray typedArray = context.obtainStyledAttributes(attrs,             R.styleable.TimeView);      int count = typedArray.getIndexCount();      try{                  for (int i = 0; i < count; ++i) {                        int attr = typedArray.getIndex(i);            // the attr corresponds to the title attribute            if(attr == R.styleable.TimeView_title) {                              // set the text from the layout               titleText = typedArray.getString(attr);               setTimeView();            } else if(attr == R.styleable.TimeView_setColor) {               // set the color of the attr "setColor"               color = typedArray.getBoolean(attr, false);               decorateText();            }         }      }              // the recycle() will be executed obligatorily      finally {         // for reuse         typedArray.recycle();      }   }   public TimeView(Context context, AttributeSet attrs, int defStyle) {      super(context, attrs, defStyle);      setTimeView();   }   private void setTimeView() {      // has the format hour.minuits am/pm      SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa");      String time = dateFormat.format(Calendar.getInstance().getTime());            if(this.titleText != null )      setText(this.titleText+" "+time);      else         setText(time);   }   private void decorateText() {      // when we set setColor attribute to true in the XML layout      if(this.color == true){         // set the characteristics and the color of the shadow         setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));         setBackgroundColor(Color.CYAN);      } else {         setBackgroundColor(Color.RED);      }   }}


MainActivity文件

public class MainActivity extends Activity {   @Override   protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_main);      TextView simpleText = (TextView) findViewById(R.id.simple);      simpleText.setText("That is a simple TextView");   }}


运行结果:



源码下载地址

http://download.csdn.net/detail/zhangxiangliang2/9873249


原创粉丝点击