android应用的界面编程
界面编程与视图(View)组件
视图组件与容器组件
ViewGroup继承了View类,但主要还是当成容器来使用。由于其是一个抽象类,通常使用其子类作为容器。
XML布局文件控制UI
setContentView();
findViewById();
<include layout="@layout/title" />---划分视图
JAVA中控制UI---不利于高层次解耦
new 控件(this);
.addView();
Context本身是一个抽象类,Activity、Service可直接作为Context使用。
混合控制UI
自定义View
继承View来派生自定义组件
重写View类的一个或多个方法
构造器
onFinishInflate()
onMeasure()
onLayout()
onSizeChanged()
onDraw()
onKeyDown() / onKeyUp()
onTouchEvent()
onTrackballEvent()
onFocusChanged()
onWindowFocusChanged()
onAttachedToWindow()
onDetachedFromWindow()
onWindowVisibilityChanged()
布局管理器---以ViewGroup作为基类派生
LinearLayout
orientation
gravity
LinearLarout.LayoutParams
layout_gravity
layout_weight
TableLayout---继承了LinearLayout
TableRow
Shrinkable
Stretchable
Collapsed
shrinkColumn
stretchColumn
collapseColumn
FrameLayout
foreground
foregroundGravity
FrameLayout:LayoutParams
layout_gravity
RelativeLayout
gravity
ignoreGravity
RelativeLayout:LayoutParams
layout_centerInParent / ...
layout_alignParentLeft / ...
layout_toRightOf / ...
layout_above / ...
layout_alignTop / ...
android.view.ViewGroup.MarginLayout Params
GridLayout
columnCount / rowCount
GridLayout.LayoutParams
layout_column / ...
layout_columnSpan /...
layout_gravity
AbsoluteLayout---已过时
layout_x / ...
TextView及其子类---继承了View
TextView 与 EditText
gravity
height
hint
singLine
shadowColor / shadowDx / shadowDy / shadowRadius
password
checkMark
background---@drawable/bg_border
shape
solid
stroke
corners
gradient
textColorHightlight
textColorHint
textSize
textAllCaps
autoLink
cursorVisible
digits
selectAllOnFocus
ellipsize
none
start
middle
end
marquee
EditText---继承了TextView
inputType
子类
AutoCompleteTextView
adapter
ExtractEditText---底层服务类,负责提供全屏输入支持
Button---继承了TextView
onClick
background---@drawable/button_selector
selector
item android : state_pressed=“true” / ...
item android : state_pressed="false" / ...
9Patch---缩放图片中某个部分
RadioButton 和 CheckBox---继承了Button
checked
RadioGroup
setOnCheckedChangeListener
ToggleButton 和 Switch---继承了Button / 切换程序中的某种状态
checked
textOff
textOn
thumb
AnalogClock 和 TextClock---时钟
AnalogClock---继承了View,在View上绘制模拟时钟
dial
hand_hour
hand_minute
TextClock---继承了TextView,以12/24小时制来显示时间
format12Hour
format24Hour
timeZone
Chronometer---计时器,继承了TextView,显示一共过去了多长时间
SystemClock.elapsedRealtime()
format
方法
setBase()
setFormat()
start() / stop()
setOnChronometerTickListener(Chronometer.OnChronometerTickListener listener)
ImageView及其子类---继承了View
src
scaleType
fitCenter
centerCrop
...
显示图片
setImageBitmap
setImageURI
setImageResource
setImageDrawable
setImageAlpha()
Bitmap
image.getDrawable().getBitmap()
creatBitmap()
子类
ImageButton
ZoomButton
ZoomControls
QuickContactBadge
assignContactFromEmail/Phone/Uri
AdapterView及其子类---继承了ViewGroup,本质是容器。派生三个子类依然是抽象类。
setAdapter(adapter);
setOnItemClickListener()
setOnItemSelectedListener()
ListView 和 ListActivity
divider
entries---@array/books
resources
string-array name=“books”
item
...
headerDividerEnabled
Adapter 接口及时实现---派生了ListAdapter、SpinnerAdapter两个子接口
ArrayAdapter---每个列表项只能是TextView
ArrayAdapter<String> adapter=new ArrayAdapter<String>(Context,textViewResourceId,数字或List)
R.layout.array_item / R.layout.checked_item
ListActivity
setListAdapter(adapter);
SimpleAdapter
new SimpleAdapter(Context,List<? extends Map<String,?>>,界面布局ID,String[],int[])
List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();
Map<String,Object> listItem = new HashMap<String,Object>();
listItem.put("header",imageIds[i]); / ...
listItems.add(listItem);
列表项组件
决定提取Map<String,?>对象中的哪些key对应的value来生成列表项
决定填充哪些组件
BaseAdapter
new BaseAdapter(){}
getCount()---列表项数目
getItem()---position处的列表项内容
getItemId()---position处的列表项ID
getView()---position处的列表项组件
AutocompleteTextView---派生自EditText,派生子类MultiAutoCompleteTextView
completionHint
completionThreshold
dropDownAnchor
dropDownHorzontalOffset
dropDownWidth
popupBackground
MultiAutoCompleteTextView
setTokenizer()
GridView---只显示一列==ListView
columnWidth
gravity
horizontalSpacing / verticalSpacing
numColumns
stretchMode
NO_STRETCH
STRETCH_SPACING
STRETCH_SPACING_UNIFORM
STRETCH_COLUMN_WIDTH
ExpandableListView---继承了ListView
childDivider
childIndicator
groupIndicator
ExpandableListAdapter接口
BaseExpandableLiatAdapter
getGroupCount()
getGroupView()
getChildCount()
getChildView()
SimpleExpandableListAdapter
SimpleCursorTreeAdapter
Spinner
entries
prompt
Gallery
不再推荐使用
使用HorizontalScrollView 和 ViewPager
AdapterViewFlipper---继承了AdapterViewAnimator
showPrevious()
showNext()
startFlipping() / stopFlipping()
animateFirstView
inAnimation / outAnimation
loopViews
autoStart
flipInterval---自动播放时间间隔
StackView---堆叠,继承了AdapterViewAnimator
拖走、拖进
showNext() / showPreviouse()
ProgressBar及其子类
ProgressBar
style
Small
Large
Inverse
Horizontal
max
progress
progressDrawable---@drawable/my_bar
layer-list
item android:id="@android:id/background" / ...
item android:id="@android:id/progress" / ...
indeterminate
setProgress()
incrementProgressBy()
标题上的进度条
requestWindowFeature()
Window.FEATURE_INDETERMINATE_PROGRESS
Window.FEATURE_PROGRESS
setProgressBarVisility() || setProgresssBarIndeterminate Visibility()
SeekBar---继承了Progress
thumb
onSeekBarChangeListener
RatingBar
isIndicator
numStarts
rating
stepSize
onRatingBarChangeListener
ViewAnimator及其子类---继承了FrameLayout
animateFirstView
inAnimation / outAnimation
ViewSwitcher---视图切换组件
setFactory(ViewSwitch.ViewFactory)
setInAnimation(this,R.anim.slide_in_right); / setOutAnimation()
set
translate android : fromXDelta / toXDelta / duration / ...
ImageSwitcher---图片切换器,继承了ViewSwitcher
提供ViewFactory,makeView()方法返回ImageView
setImageDrawable() / setImageResource() / setImageURI()
TextSwitcher---文本切换器,继承了ViewSwitche
ViewFactory的makeView()方法返回TextView组件
onClick
ViewFlipper---继承了ViewAnimator
addView()
showPrevious() / showNext()
杂项组件
Toast
.makeText()
.show()
.setView()
CalendarView---日历视图
setOnDateChangeListener()
onSelectedDayChange()
firstDayOfWeek
showWeekNumber / showWeekCount
selectedWeekBackgroundColor
focusedMonthDateColor
weekSeparatorLineColor
unfocusedMonthDateColor
DatePicker 和 TimePicker---日期、时间选择器,继承了FrameLayout
OnDateChangedLiatener
OnTimerChangedListener
calendarViewShown
endYear
maxDate / minDate
spinnersShown
startYear
datePicker.init(year,month,day,new OnDateChangeeListener(){})
timePicker.setOnTimeChangedListener(new OnTimeChangedListener(){})
NumberPicker
setMinValue() / setMaxValue()
setValue()
setOnValueChangedListener()
SearchView
setIconifiedByDefault()
setSubmitButtonEnabled()
setQueryHint()
setOnQueryTextListener()
OnQueryTextChange()
TextUtils.isEmpty(newText)
.clearTextFilter()
.setFilterText(newText)
OnQueryTextSubmit()
配套ListView,可增加自动完成功能
TabHost---选项卡,结合使用TabWidget、TabSpec---不再推荐使用,使用Fragment
TabWidget---标题条
TabSpec---Tab页面
定义TabHost组件
继承TabActivity
调用.getTabHost()获取tabHost对象
对象方法创建、添加选项卡
newTabSpec(String tag)
.setIndicator()
.setContent()
addTab(TabHost.TabSpec tabSpec)
OnTabChangeListener
ScrollView---继承了FramLayout,只能包含一个组件,添加垂直滚动条
HorizontalScrollView---水平滚动条
Notification
Notification.Builder
setDefaults()
setAutoCancel()
setContentTitle()
setContentText()
setSmallIcon()
setLargeIcon()
setTick()
setContentIntent()
PendingIntent p=PendingIntent.getActivity(MainActivity.this,0,intent,0);
getSystemService(NOTIFICATION_SERVICE)获取NotificationManager服务
通过构造器创建Notification对象
设置属性
通过NotificationManager发送Notification
notify()
cancel()
对话框
AlertDialog
AlertDialog.Builder
setTitle() || setCustomTitle
setIcon()
... || setMessage()、setItems()、setSingleChoiceItem()、setMultiChoiceItems()、setAdapter()、setView()
setPositiviButton()、setNegativeButton()、setNeutralButton()
create() || show()
对话框风格的窗口
AndroidManifest
activity android:theme="@android:style/theme.Material.Dialog"
PopupWindow---浮动窗口
创建PopupWindow对象
showAsDropDown(View v)下拉组件显示 || showAtLocation()在指定位置显示
dismiss()
DatePickerDialog、TimePickerDialog
new 创建实例
Calendar c=Calendar.getInstance();
new DatePickerDialog(
this,
new DatePickerDialog.OnDateSetListener(){
@override
public void onDateSet(
DatePicker dp,
int year,
int month,
int dayOfMonth)
{...}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)
)
.show();
new TimePickerDialog(
this,
new TimePickerDialog.OnTimeSetListener(){
@override
public void onTimeSet(
TimePicker tp,
int hourOfDay,
int minute)
{...}
},
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true---采取24小时制
)
.show();
show()
ProgressDialog
setIndeterminate()
setMax
setMessage
setProgress
setProgressStyle
.show
菜单---Android不再强制要求手机提供MENU按键,因此推荐使用ActionBar代替菜单
Menu 和 Submenu---接口
Menu接口
MenuItem add(int titlleRes)
MenuItem add(int groupId,int itemId,int Order,CharSequence title)
MenuItem add(int groupId,int itemId,int Oder,int titleRes)
MenuItem add(CharSequence title)
SubMenu addSubMenu(int titleRes)
SubMenu addSubMenu(int groupId,int itemId,int Order,int titleRes)
SubMenu addSubMenu(ChatSequence title)
SubMenu addSubMenu(int groupId,int itemId,int Order,CharSequence title)
SubMenu接口---继承了Menu,代表一个子菜单
SubMenu setHeaderIcon(Drawable icon || int iconRes)
SubMenu setHeaderTitle(int titleRes || CharSequence title)
SubMenu setHeaderView(View view)
添加菜单
重写onCreatOptionsMenu(Menu menu)
return super.onCreatOptionsMenu(menu)
重写onOptionsItemSelected(MenuItem mi)
switch(mi.getItemId())
return true
android 5.0采用Material主题,这种主题不会显示子菜单的标题
监听器---允许为不用菜单项分别绑定监听器---不推荐(代码臃肿)
setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener)
多选及单选菜单
setCheckable(boolean checkable)---默认多选
setGroupCheckable(int group,boolean checkable,boolean exclusive)---exclusive为true是,将是一组单选菜单项
setAlphabeticShortcut(char alphachar)
setNumericShortcut(char numericChar)
setShortcut(char numericChar,char alphaChar)
关联Activity
调用MenuItem的setIntent(Intent intent)
上下文菜单---ContextMenu继承了Menu
重写onCreatContextMenu(ContextMenu menu,View source,ContextMenu.ContextMenuInfo menuInfo)
调用registerForContextMenu(View view)为view组件注册上下文菜单
重写onContextItemSelexted(MenuItem mi)
XML定义菜单---推荐使用,更好的解耦
app\src\main\res\menu
menu
item
android.alphabeticShortcut
android.numericShortcut
group
checkableBehavior
none
all
single
menuCategory
container
system
secondary
alternatice
visible
enable
重写onCreateOptionsMenu / onCreateContextMenu
调用MenuInflater对象的inflate方法加载指定的资源菜单
PopupMenu---弹出式菜单
new PopupMenu(Context context,View anchar)
调用MenuInflater的inflate()
调用PopupMenu的show()
活动条---顶部显示,可显示活动项(Action Item)
ActionBar
getActionBar();
.show()
.hide()
ActionBar显示选项菜单---可将选项菜单显示成Action Item
MenuItem
setShowAsAction(int actionEnum)
SHOW_AS_ACTION_ALWAYS
SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
SHOW_AS_ACTION_IF_ROOM
SHOW_AS_ACTION_NEVER
SHOW_AS_ACTION_WITH_TEXT
app\src\main\res\menu
item
android : showAsAction
启动程序图标导航---将应用程序图标转换为可点击的图标
setDisplayHomeAsUpEnabled(boolean showHomeAsUp)
setDisplayOptions(int options)
setDisplayShowHomeEnabled(boolean showHome)
setHomeButtonEnabled(boolean enabled)
android.R.id.home:
添加Action View---ActionBar不仅可以显示Action Item,item添加如下属性
android : actionViewClass---实现类
android.widget.SearchView
android : actionLayout---视图资源
@layout/clock
<AnalogClock ... />
ActionBar实现Tab导航---结合Fragment,过时的方式,推荐使用图标导航
调用ActionBar的setNavigationMode(ActionBar.NAVIGATION_MODE_TABS)
调用ActionBar的addTab()添加标签,并添加事件监听器
actionBar.addTab(actionBar.newTab().setText("...").setTabListener(this));
onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction)
Android Studio中创建Tabbed Activity
Swipe Views
Action Bar Tabs
Action Bar Spinner
Android 3.0以前的Fragment支持
继承了android.support.v4.app.fragment
FragmentActivity
getSupportFragmentManager()
ViewPager
fragment容器,管理多个fragment
setAdapter()
setOnPagerChangeListener()
onPageSelected()
setSelectedNavigationItem()
setCurrentItem(tab.getPosition())
FragmentPagerAdapter
为ViewPager提供多个Fragment
getItem()
getCount()
getPagerTitle()
PagerTitleStrip
与ViewPager结合使用,在ViewPager上显示导航条
ActionBar实现下拉式导航---结合Fragment
调用ActionBar的actionBar.setNavigationMode(ActionBar.NAVIGETION_MODE_LIST)
调用ActionBar的setListNavigationCallbacks(SpinnerAdapter adapter,ActionBar.onNavigationListener callback)添加多个列表项,并为每个列表项设置事件监听器
onNavigationItemSelected()
小结:
第二章的内容非常多,篇幅也高达本书的20%。然其中很多控件已经不再推荐使用,甚至不能使用。关于控件的分类也有很多种,个人觉得没有优劣,就像一个功能会有很多种实现的方法,至于具体用什么就看个人喜好了。
Android官方文档是一个很好的学习途径。https://developer.android.google.cn/guide
生活感悟:
-
大智若愚,戒骄戒躁。
-
凡是冷静思考,考虑问题的深层含义,用心感受背后的真实原因。
- 请保持精致,因为你永远不知道你会在什么时候突然想去见某个人,或者在某个时候突然遇到那个让你怦然心动的人。