Pro Android 4 第六章 构建用户界面以及使用控件(一)
目前为止,我们已经介绍了android的基础内容,但是还没开始接触用户界面(UI)。本章我们将开始探讨用户界面和控件。我们先讨论一下android中UI设计的一般原理,然后我们在介绍一下android sdk自带的UI控件,这些是你将要创建的UI的基本模块。我们还会讨论view 适配器和layout管理器。View适配器用来想控件提供数据,然后控件对数据进行显示。数据可以是数组,数据库或其它数据源。正如其名字所示,layout管理器负责管理控件在屏幕中的显示位置。另外,我们还会学习styles和themes,它们可以封装控件的显示属性以便更好的创建和维护。
| 名称 | 描述 |
| view,widget,control | 每一个都代表一个ui元素。例如一个按钮,栅格,列表,窗口,对话框等等。在本章,这几个名词可以互换使用 |
| container | 这是一个可以容纳其他视图的视图。例如栅格grid可以视为一个容器,因为它包含多个cells,而每个cell都是一个view |
| layout | 这是容器和视图的一种可视化表示,可以包含其它布局 |
Listing 6–1. Creating a Simple User Interface Entirely in Code
package com.androidbook.controls;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
private LinearLayout nameContainer;
private LinearLayout addressContainer;
private LinearLayout parentContainer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);createNameContainer();
createAddressContainer();
createParentContainer();
setContentView(parentContainer);
}
private void createNameContainer()
{
nameContainer = new LinearLayout(this);nameContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
nameContainer.setOrientation(LinearLayout.HORIZONTAL);
TextView nameLbl = new TextView(this);
nameLbl.setText("Name: ");
TextView nameValue = new TextView(this);
nameValue.setText("John Doe");
nameContainer.addView(nameLbl);
nameContainer.addView(nameValue);
}
private void createAddressContainer()
{
addressContainer = new LinearLayout(this);addressContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
addressContainer.setOrientation(LinearLayout.VERTICAL);
TextView addrLbl = new TextView(this);
addrLbl.setText("Address:");
TextView addrValue = new TextView(this);
addrValue.setText("911 Hollywood Blvd");
addressContainer.addView(addrLbl);
addressContainer.addView(addrValue);
}
private void createParentContainer()
{
parentContainer = new LinearLayout(this);parentContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
parentContainer.setOrientation(LinearLayout.VERTICAL);
parentContainer.addView(nameContainer);
parentContainer.addView(addressContainer);
}
addressContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- NAME CONTAINER -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="Name:" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="John Doe" />
</LinearLayout>
<!-- ADDRESS CONTAINER -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="wrap_content">
<TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="Address:" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="911 Hollywood Blvd." />
</LinearLayout>
Listing 6–3. Creating a User Interface in XML with IDs
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- NAME CONTAINER -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="@string/name_text" />
<TextView android:id="@+id/nameValue"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout><!-- ADDRESS CONTAINER -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="@string/addr_text" />
<TextView android:id="@+id/addrValue"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>
Listing 6–4. strings.xmlFile for Listing 6–3
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Common Controls</string>
<string name="name_text">Name:</string>
<string name="addr_text">Address:</string>
setContentView(R.layout.main);
TextView nameValue = (TextView)findViewById(R.id.nameValue);
nameValue.setText("John Doe");
TextView addrValue = (TextView)findViewById(R.id.addrValue);
addrValue.setText("911 Hollywood Blvd.");
FILL_PARENT vs. MATCH_PARENT
.png)
Listing 6–6. Using Linkify on Text in a TextView
TextView tv =(TextView)this.findViewById(R.id.tv);
tv.setAutoLinkMask(Linkify.ALL);
tv.setText("Please visit my website, http://www.androidbook.com
davemac327@gmail.com.");
<AutoCompleteTextView android:id="@+id/actv"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
AutoCompleteTextView actv = (AutoCompleteTextView) this.findViewById(R.id.actv);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,new String[] {"English", "Hebrew", "Hindi", "Spanish", "German", "Greek" });
Listing 6–8. Using the MultiAutoCompleteTextView Control
<MultiAutoCompleteTextView android:id="@+id/mactv"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) this .findViewById(R.id.mactv);
ArrayAdapter<String> aa2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
new String[] {"English", "Hebrew", "Hindi", "Spanish", "German", "Greek" });
mactv.setAdapter(aa2);
Listing 6–9. Handling Click Events on a Button
<Button android:id="@+id/button1"
android:text="@string/basicBtnLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Button button1 = (Button)this.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.androidbook.com"));
startActivity(intent);
}
<Button ... android:onClick="myClickHandler" ... />
public void myClickHandler(View target) {
switch(target.getId()) {case R.id.button1:...
ImageButton控件
<ImageButton android:id="@+id/imageButton2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="myClickHandler"
android:src="@drawable/icon" />
ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setImageResource(R.drawable.icon);
Listing 6–12.Using a Selector with an ImageButton
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/icon" /> <!-- default -->
<ToggleButton android:id="@+id/cctglBtn"
android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Toggle Button"android:textOn="Stop"android:textOff="Run"/>
因为ToggleButton中的开关文本是两个独立的属性,所以其android:text属性是不起作用的。该属性可以使用,是因为它是从TextView出继承而来。但是在本例中,你无需使用它。
Listing 6–14. Creating Check Boxes
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/chickenCB" android:text="Chicken" android:checked="true"
android:layout_width=“wrap_content" android:layout_height="wrap_content" />
<CheckBox android:id="@+id/fishCB" android:text="Fish"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<CheckBox android:id="@+id/steakCB" android:text="Steak" android:checked="true"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
Listing 6–15.Using Check Boxes in Code
public class CheckBoxActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.checkbox);
CheckBox fishCB = (CheckBox)findViewById(R.id.fishCB);
if(fishCB.isChecked())
fishCB.toggle(); // flips the checkbox to unchecked if it was checked
fishCB.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
Log.v("CheckBoxActivity", "The fish checkbox is now "+ (isChecked?"checked":"not checked"));
}});
}
Listing 6–16.Using Check Boxes in Code with android:onClick
public void myClickHandler(View view) {
switch(view.getId()) {
case R.id.steakCB:
Log.v("CheckBoxActivity", "The steak checkbox is now " +(((CheckBox)view).isChecked()?"checked":"not checked"));
}
Listing 6–17.Using Android RadioButtonWidgets
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RadioGroup android:id="@+id/rBtnGrp" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="vertical" >
<RadioButton android:id="@+id/chRBtn" android:text="Chicken"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/fishRBtn" android:text="Fish" android:checked="true"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/stkRBtn" android:text="Steak"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</RadioGroup>
steakBtn.setChecked(true);
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><RadioButton android:id="@+id/anotherRadBtn" android:text="Outside"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<RadioGroup android:id="@+id/radGrp"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<RadioButton android:id="@+id/chRBtn" android:text="Chicken"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/fishRBtn" android:text="Fish"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/stkRBtn" android:text="Steak"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<TextView android:text="My Favorite"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</RadioGroup>
Listing 6–19.Adding a RadioButtonto a RadioGroupin Code
RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
RadioButton newRadioBtn = new RadioButton(this);
newRadioBtn.setText("Pork");
Listing 6–20.Using a RadioGroup Programmatically
public class RadioGroupActivity extends Activity {
protected static final String TAG = "RadioGroupActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.radiogroup);
RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
int checkedRadioButtonId = radGrp.getCheckedRadioButtonId();
radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int id) {
switch(id) {case -1:
Log.v(TAG, "Choices cleared!");break;
case R.id.chRBtn:
Log.v(TAG, "Chose Chicken");break;
case R.id.fishRBtn:
Log.v(TAG, "Chose Fish");break;
case R.id.stkRBtn:
Log.v(TAG, "Chose Steak");break;
default:
Log.v(TAG, "Huh?");break;
}
}});
}
Listing 6–21. ImageViews in XML and in Code
<ImageView android:id="@+id/image1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:src="@drawable/icon" />
<ImageView android:id="@+id/image2"
android:layout_width="125dip" android:layout_height="25dip"
android:src="#555555" />
<ImageView android:id="@+id/image3"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<ImageView android:id="@+id/image4"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:src="@drawable/manatee02"
android:scaleType="centerInside"
android:maxWidth="35dip" android:maxHeight="50dip"
/>
ImageView imgView = (ImageView)findViewById(R.id.image3);
imgView.setImageResource( R.drawable.icon );
imgView.setImageBitmap(BitmapFactory.decodeResource( this.getResources(), R.drawable.manatee14) );
imgView.setImageDrawable( Drawable.createFromPath("/mnt/sdcard/dave2.jpg") );
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:id="@+id/dateDefault"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<DatePicker android:id="@+id/datePicker"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/timeDefault"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TimePicker android:id="@+id/timePicker"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.datetimepicker);
TextView dateDefault = (TextView)findViewById(R.id.dateDefault);TextView timeDefault = (TextView)findViewById(R.id.timeDefault);DatePicker dp = (DatePicker)this.findViewById(R.id.datePicker);// The month, and just the month, is zero-based. Add 1 for display.dateDefault.setText("Date defaulted to " + (dp.getMonth() + 1) + "/" +dp.getDayOfMonth() + "/" + dp.getYear());// And here, subtract 1 from December (12) to set it to Decemberdp.init(2008, 11, 10, null);
TimePicker tp = (TimePicker)this.findViewById(R.id.timePicker);java.util.Formatter timeF = new java.util.Formatter();timeF.format("Time defaulted to %d:%02d", tp.getCurrentHour(),tp.getCurrentMinute());timeDefault.setText(timeF.toString());tp.setIs24HourView(true);tp.setCurrentHour(new Integer(10));tp.setCurrentMinute(new Integer(10));
.png)
Listing 6–24. Adding a DigitalClockor an AnalogClockin XML
<DigitalClock
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<AnalogClock
android:layout_width="wrap_content" android:layout_height="wrap_content" />
Listing 6–25.Creating a MapViewControl via XML Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:layout_width="fill_parent"android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="myAPIKey"
/>
<Spinner android:id="@+id/spinner"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/values/planets.xml -->
<resources>
<string-array name="planets">
<item>Mercury</item><item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
Pro Android 4 第六章 构建用户界面以及使用控件(一)的更多相关文章
- android 学习六 构建用户界面和使用控件
1.常用Android控件最终都会继承自View类 2.ViewGroup是一些布局类列表的基类,包括View和ViewGroup 3.构造界面的三种方法 a.完全使用代码(太灵活,而不好维护) ...
- 【WPF学习】第六十四章 构建基本的用户控件
创建一个简单用户控件是开始自定义控件的好方法.本章主要介绍创建一个基本的颜色拾取器.接下来分析如何将这个控件分解成功能更强大的基于模板的控件. 创建基本的颜色拾取器很容易.然而,创建自定义颜色拾取器仍 ...
- android开发游记:meterial design 5.0 开源控件整套合集 及使用demo
android 的5.0公布不光google官方给出了一些新控件,同一时候还给出了一套符合material design风格的设计标准,这套标准将未来将覆盖google全部产品包括pc端,站点,移动端 ...
- 通过编写串口助手工具学习MFC过程——(六)添加Edit编辑框控件
通过编写串口助手工具学习MFC过程 因为以前也做过几次MFC的编程,每次都是项目完成时,MFC基本操作清楚了,但是过好长时间不再接触MFC的项目,再次做MFC的项目时,又要从头开始熟悉.这次通过做一个 ...
- Android学习之基础知识五—RecyclerView(滚动控件)
RecyclerView可以说是增强版的ListView,不仅具有ListVIew的效果,还弥补许多ListView的不足. 一.RecyclerView的基本用法 与百分比布局类似,Recycler ...
- 如何用 Swift 语言构建一个自定控件
(via:破船之家,原文:How To Make a Custom Control in Swift) 用户界面控件是所有应用程序重要的组成部分之一.它们以图形组件的方式呈现给用户,用户可以通过它 ...
- Android怎么使用字体图标 自定义FontTextView字体图标控件-- 使用方法
首先我想说明一下字体图标的好处,最大的好处就是自适应了,而且是使用TextView 不用去切图,是矢量图 灵活调用 第一步我要说明一下一般字体图标的来源,我这里使用的是 --阿里巴巴矢量图标库 -网 ...
- android 在一个scrollView里面嵌套一个需要滑动的控件(listView、gridView)
package cn.via.dageeeOrderFood.widget; import android.content.Context; import android.graphics.Point ...
- Android 4.0 新增的显示数据集的桌面控件
setRemoteAdapter (int viewId, Intent intent):该方法可以使用 Intent 更新 RemoteViews 中viewId 对应的组件. 上面方法的 Inte ...
随机推荐
- GDKOI2015
problems http://gdoi.sysu.edu.cn/wp-content/uploads/2015/03/GDKOI-2015-day1.pdf http://gdoi.sysu.edu ...
- HDU4453--Looploop (Splay伸展树)
Looploop XXX gets a new toy named Looploop. The toy has N elements arranged in a loop, an arrow poin ...
- 【案例】舒邑:一个女装品牌的奇葩打法-@i黑马
[案例]舒邑:一个女装品牌的奇葩打法-@i黑马 [案例]舒邑:一个女装品牌的奇葩打法
- WebView使用
WebView是View的一个子类,可以让你在activity中显示网页. 可以在布局文件中写入WebView:比如下面这个写了一个填满整个屏幕的WebView: <?xml version=& ...
- 画8_hdu_1256(图形).java
画8 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submiss ...
- [AngularJS] Transforming raw JSON data to meaningful output in AngularJS
angular.module('APP', []) .controller('MainController', function($scope, UserConstants){ var user = ...
- Android开发所有视频教程汇总
1.Mars的Android开发视频教程作者讲解的很详细,很全面,系统.以前出了两套视频,分别是<Java4Android视频教程>.<Android视频教程>,以及最新刚新出 ...
- oracle之case when
oracle case when 的用法 http://www.cnblogs.com/xiaowu/archive/2011/08/17/2143445.html(转) http://www.cnb ...
- 主运行循环main run loop的一些理解
应用主运行循环负责处理所有用户相关的事件.UIApplication对象在应用启动时安装主运行循环并且使用此循环去处理事件和处理基于视图的界面更新.正如名字所表明的,该主运行循环是在应用的主线程app ...
- js中window.print()去除页眉页脚
//jsp打印时去除页眉页页脚 打印前加入下面代码即可 var HKEY_Root,HKEY_Path,HKEY_Key; HKEY_Root="HKEY_CURRENT_USER" ...