Android 4学习(9):用户界面 - THE ANDROID WIDGET TOOLBOX
阅读原文时间:2023年07月09日阅读:2

Android内置了很多View,包括:

  • TextView
  • EditText
  • Chronometer
  • ListView
  • Spinner
  • Button
  • ToggleButton
  • ImageButton
  • CheckBox
  • RedioButton
  • ViewFlipper
  • VideoView
  • QuickContactBadge
  • ViewPager

关于View更多的信息,可以参考:http://developer.android.com/guide/tutorials/views/index.html

总的来说,有三种方法来创建新的View:

  • 修改已有的View。
  • 使用多个已有的View组成新的复合View
  • 从头新建一个View

修改已有的View

创建某种View的子类并重写父类的方法,即可通过修改已有View来创建自定义的View,例如:

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.TextView;
public class MyTextView extends TextView {
  public MyTextView (Context context, AttributeSet attrs, int defStyle)
  {
  super(context, attrs, defStyle);
  }
  public MyTextView (Context context) {
  Super(context);
  }
  public MyTextView (Context context, AttributeSet attrs) {
  super(context, attrs);
  }
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
  [ … Perform some special processing … ]
  [ … based on a particular key press … ]
  // Use the existing functionality implemented by
  // the base class to respond to a key press event.
  return super.onKeyDown(keyCode, keyEvent);
  }
}

创建复合控件View

复合控件由多个View组成,是ViewGroup的子类。通过继承ViewGroup并重写父类的构造函数,在构造过程中inflate某个Layout,是常用的生成复合控件的方法之一,例如:

public class ClearableEditText extends LinearLayout {
  EditText editText;
  Button clearButton;
  public ClearableEditText(Context context) {
  super(context);
  // Inflate the view from the layout resource.
  String infService = Context.LAYOUT_INFLATER_SERVICE;
  LayoutInflater li;
  li = (LayoutInflater)getContext().getSystemService(infService);
  li.inflate(R.layout.clearable_edit_text, this, true);
  // Get references to the child controls.
  editText = (EditText)findViewById(R.id.editText);
  clearButton = (Button)findViewById(R.id.clearButton);
  // Hook up the functionality
  hookupButton();
  }
}

配置文件:


http://schemas.android.com/apk/res/android”   android:orientation=”vertical”   android:layout\_width=”match\_parent”   android:layout\_height=”wrap\_content”>