[Android5 系列二] 1. 全实例之控件(Widget)

前言

android.view.View 视图类是widgets 的基类, 有很多的扩展类, 包括文本视图TextView、图像视图ImageView、进度条ProgressBar 、视图组ViewGroup 等。

具体的结果如下图:

创建Android Project

这里使用的是Eclipse 的IDE 来进行Android 开发。

官方推荐的IDE已经是基于IntelliJ IDEA  的studio了。

1. File --> New --> Android --> Android Application Project

如下输入后, 下一步:

2.一路next 到 选择 Blank Activity

3. 一路next , finish

实例预览介绍

这里的实例使用的方式是:

在 MainActivity 中定义一些按钮, 点击按钮进入到实际效果的activity 中。

修改MainActivity

修改 activity_main.xml, 完整内容如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.oscar999.androidstudy.MainActivity" >

    <Button
        android:id="@+id/widgetbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/my_widget" />

</RelativeLayout>

修改 strings.xml, 内容如下

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidStudy</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="my_widget">My Widget</string>
</resources>

到这里, 运行一下看一下效果:

添加点击以上按钮的activity

新建 activity   -->   MyWidgetActivity

修改MainActivity.java , 让点击 My Widget 按钮进入这个activity。

主要是修改 onCreate 方法, 修改后的完整代码如下:

package com.oscar999.androidstudy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final Button widgetButton = (Button) findViewById(R.id.widgetbutton);
		widgetButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, MyWidgetActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

接下来就是完善 MyWidgetActivity 的相关内容了。

添加三个按钮

1. 修改 activity_my_widget.xml, 放置三个button, 完整内容如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <!-- Regular Sized Button -->
	<Button android:id="@+id/button_normal"
	    android:text="@string/button_normal"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>
	<!-- Small Button -->
	<Button android:id="@+id/button_small"
	    style="?android:attr/buttonStyleSmall"
	    android:text="@string/button_small"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>
	<!-- Toggle Button -->
	<ToggleButton android:id="@+id/button_toggle"
	    android:text="@string/button_toggle"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>
</LinearLayout>

2. strings.xml  添加如下配置

    <string name="button_normal">Normal</string>
    <string name="button_small">Small</string>
    <string name="button_toggle">On</string>  

运行一下, 效果如下:

添加图像区域- ImageView

和上面Button 的添加方式类似:

1. 在 activity_my_widget.xml 中添加如下内容

	<ImageView android:src="@drawable/image_sample1"
	    android:contentDescription="@string/image_sample1"
	    android:adjustViewBounds="true"
		android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>

2. 随便找一个图片文件, 命名为 image_sample1.png, 放入 res/drawable-hdpi 目录下(其他类似的 drawable 目录也可以放)

3. string.xml 中添加如下内容:


<string name="image_sample1">Image Sample</string> 

运行一下, 效果如下:


更多的控件

其他的空间像:图像按钮(ImageButton), 进度条(ProgressBar), 可编辑文本区域(EditText), 复选框(CheckBox), 单选按钮组(RadioGroup), 文本区域(TextView), 旋转按钮(Spinner)等控件。具体的定义方式可以参照 API 来进行。

除了系统提供的View 之外, 也可以自定义视图。

自定义视图

1。 新增Class : com.oscar999.androidstudy.view.MyView 继承自View

package com.oscar999.androidstudy.view;

import com.oscar999.androidstudy.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {
	private Paint mTextPaint;
	private int mAscent;
	private String mText;

	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initMyView();

		TypedArray a = context
				.obtainStyledAttributes(attrs, R.styleable.MyView);

		CharSequence s = a.getString(R.styleable.MyView_text);
		if (s != null) {
			setText(s.toString());
		}

		// Retrieve the color(s) to be used for this view and apply them.
		// Note, if you only care about supporting a single color, that you
		// can instead call a.getColor() and pass that to setTextColor().
		setTextColor(a.getColor(R.styleable.MyView_textColor, 0xFF000000));

		int textSize = a
				.getDimensionPixelOffset(R.styleable.MyView_textSize, 0);
		if (textSize > 0) {
			setTextSize(textSize);
		}

		a.recycle();
		// TODO Auto-generated constructor stub
	}

	private final void initMyView() {
		// create text paint to setting text
		mTextPaint = new Paint();
		mTextPaint.setAntiAlias(true);
		// Must manually scale the desired text size to match screen density
		mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
		mTextPaint.setColor(0xFF000000);
		setPadding(3, 3, 3, 3);
	}

	public void setText(String text) {
		mText = text;
		// Call this when something has changed which has invalidated the layout
		// of this view. This will schedule a layout pass of the view tree.
		requestLayout();
		// Invalidate the whole view. If the view is visible,
		// onDraw(android.graphics.Canvas) will be called at some point in the
		// future. This must be called from a UI thread. To call from a non-UI
		// thread, call postInvalidate().
		invalidate();
	}

	/**
	 * Sets the text size for this label
	 *
	 * @param size
	 *            Font size
	 */
	public void setTextSize(int size) {
		// This text size has been pre-scaled by the getDimensionPixelOffset
		// method
		mTextPaint.setTextSize(size);
		requestLayout();
		invalidate();
	}

	/**
	 * Sets the text color for this label.
	 *
	 * @param color
	 *            ARGB value for the text
	 */
	public void setTextColor(int color) {
		mTextPaint.setColor(color);
		invalidate();
	}

	/**
	 * @see android.view.View#measure(int, int)
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// This mehod must be called by onMeasure(int, int) to store the
		// measured width and measured height. Failing to do so will trigger an
		// exception at measurement time.
		setMeasuredDimension(measureWidth(widthMeasureSpec),
				measureHeight(heightMeasureSpec));
	}

	/**
	 * Determines the width of this view
	 *
	 * @param measureSpec
	 *            A measureSpec packed into an int
	 * @return The width of the view, honoring constraints from measureSpec
	 */
	private int measureWidth(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);
		if (specMode == MeasureSpec.EXACTLY) {
			// We were told how big to be
			result = specSize;
		} else {
			// Measure the text

			result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
					+ getPaddingRight();
			if (specMode == MeasureSpec.AT_MOST) {
				// Respect AT_MOST value if that was what is called for by
				// measureSpec

				result = Math.min(result, specSize);
			}
		}

		return result;
	}

	/**
	 * Determines the height of this view
	 *
	 * @param measureSpec
	 *            A measureSpec packed into an int
	 * @return The height of the view, honoring constraints from measureSpec
	 */
	private int measureHeight(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		mAscent = (int) mTextPaint.ascent();
		if (specMode == MeasureSpec.EXACTLY) {
			// We were told how big to be
			result = specSize;
		} else {
			// Measure the text (beware: ascent is a negative number)

			result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop()
					+ getPaddingBottom();
			if (specMode == MeasureSpec.AT_MOST) {
				// Respect AT_MOST value if that was what is called for by
				// measureSpec
				result = Math.min(result, specSize);
			}
		}
		return result;
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawText(mText, this.getPaddingLeft(), this.getPaddingTop()
				- mAscent, mTextPaint);
	}

}

2. 在 res/layouts下新增 attrs.xml

<resources>

	<declare-styleable name="MyView">
	    <attr name="text" format="string"/>
	    <attr name="textColor" format="color"/>
	    <attr name="textSize" format="dimension"/>
	</declare-styleable>
</resources>

3. 添加 red.png, blue.png, green.png 到 drawable 目录下

4. 修改 activity_my_widget.xml, 完整内容如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.oscar999.androidstudy"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <!-- Regular Sized Button -->
	<Button android:id="@+id/button_normal"
	    android:text="@string/button_normal"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>
	<!-- Small Button -->
	<Button android:id="@+id/button_small"
	    style="?android:attr/buttonStyleSmall"
	    android:text="@string/button_small"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>
	<!-- Toggle Button -->
	<ToggleButton android:id="@+id/button_toggle"
	    android:text="@string/button_toggle"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>

	<!-- Image View-->
	<ImageView android:src="@drawable/image_sample1"
	    android:contentDescription="@string/image_sample1"
	    android:adjustViewBounds="true"
		android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>

    <!-- My View-->
    <com.oscar999.androidstudy.view.MyView
        android:background="@drawable/red"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:text="Red"
        />
    <com.oscar999.androidstudy.view.MyView
        android:background="@drawable/blue"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:text="Blue" app:textSize="20sp"
        />
    <com.oscar999.androidstudy.view.MyView
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:text="Green" app:textColor="#ffffff"
        />  

</LinearLayout>

5. 运行一下, 效果如下:

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-10 07:50:55

[Android5 系列二] 1. 全实例之控件(Widget)的相关文章

WPF系列之二:解耦View层控件事件与ViewModel层事件的响应

以前的做法: 1.当项目的时间比较紧迫的时候,对UI层中控件的事件的处理,往往采取的是类似Winform中最简单的做法,直接做一个事件的Handler直接去调用VM层的方法. 2.控件只有一个Command属性,其它的事件的处理方法没有办法和ViewModel层进行解耦的时候往往也采取上面提到的方法. 如下图所示: 新的做法: 为了实现事件的处理与View层的解耦,我们可以利用WPF提供的附加属性来为需要的事件添加附加行为.附加属性扮演了一个在View层与Model层牵线的角色. 需要下面三个步

我教女朋友学编程Html系列(6)—Html常用表单控件

做过网页的人都知道,html表单控件十分重要.基本上我们注册会员.登录用户,都需要填写用户名.密码,那些框框都是表单控件. 本来今天就想写一些常用的html表单控件,于是开始搜资料,找到了一个网页,作者的写作思路和我的基本相同,不过不足的是缺少效果图. 我打算结合着这位仁兄的文章补充一下,增加一些效果图,另外把一些新内容也补充进去,原文的地址是: HTML表单(Forms) 我站在这位仁兄的肩膀上写作,再增加一些东西,配上一些图,我想,效果应该很好,接着就跟着我来学习吧. HTML表单(Form

asp.net总结(二)——HTML与WEB控件

关于Html控件与Web控件的使用,我还是首先用一张图来展示一下: (一)HTML控件 就是我们通常的说的html语言标记,这些语言标记在已往的静态页面和其他网页里存在,不能在服务器端控制的,只能在客户端通过javascript和vbscript等程序语言来控制.<input type="button" id="btn" value="button"/>  使用范围: 1.HTML控件直接与浏览器界面交互,一些属性可以很好地设计浏览器

桌面控件Widget的使用

开发者文档中详细介绍了Widget的使用方法  file:///D:/Program%20Files%20(x86)/Andriod/android-sdks/docs/guide/topics/appwidgets/index.html 最终效果展示: 1. 首先建立AppWidgetProvider的实体类(AppWidgetProvider class implementation)MyWidget public class AppWidgetProvider extends Broadc

自定义控件系列之应用篇——自定义标题栏控件

一.问题概述 通过之前的应用练习其实我们已经对自定义控件有了一定的掌握(查看自定义控件系列其余文章:基础篇.应用篇之圆形进度条),但还是要不断做一些应用锻炼思维和熟练度,接下来我们再运用自定义控件编写一个新闻列表的标题栏,该标题栏控件有三种样式,效果如图所示: 样式1: 样式2: 样式3: 并且标题文字.左右图标可自由变换.实现步骤如下: 二.实现步骤 1.编写自定义组件HeaderView扩展LinearLayout public class HeaderView extends Linear

【转】VS2010/MFC编程入门之二十五(常用控件:组合框控件Combo Box)

原文网址:http://www.jizhuomi.com/software/189.html 上一节鸡啄米讲了列表框控件ListBox的使用,本节主要讲解组合框控件Combo Box.组合框同样相当常见,例如,在Windows系统的控制面板上设置语言或位置时,有很多选项,用来进行选择的控件就是组合框控件.它为我们的日常操作提供了很多方便. 组合框控件简介 组合框其实就是把一个编辑框和一个列表框组合到了一起,分为三种:简易(Simple)组合框.下拉式(Dropdown)组合框和下拉列表式(Dro

仿酷狗音乐播放器开发日志二十一 开发动态调色板控件(附源代码)

转载请说明原出处,谢谢~~ 上一篇仿酷狗日志结束后,整个换肤功能就仅仅剩下调色板功能没有做了.我本以为会非常easy.可是研究了酷狗的调色板功能后发现不是那么简单的事情.首先看一下酷狗的调色板的样子: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemh1aG9uZ3NodQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" > waterm

MFC编程入门之二十六(常用控件:滚动条控件ScrollBar)

回顾上一节,讲的是组合框控件Combo Box的使用.本节详解滚动条控件Scroll Bar的相关内容. 滚动条控件简介 滚动条大家也很熟悉了,Windows窗口中很多都有滚动条.前面讲的列表框和组合框设置了相应属性后,如果列表项显示不下也会出现滚动条.滚动条分为水平滚动条(Horizontal Scroll Bar)和垂直滚动条(Vertical Scroll Bar)两种.滚动条中有一个滚动块,用于标识滚动条当前滚动的位置.我们可以拖动滚动条,也可以用鼠标点击滚动条某一位置使滚动块移动. 从

开发ActiveX控件调用另一个ActiveX系列1——开发一个MFC ActiveX控件

ActiveX开发的教程有很多,我也从中受益匪浅,例如以下这几篇: 基本教程:http://www.cnblogs.com/guenli/articles/1629915.html 注意事项:http://jon-lt.iteye.com/blog/1676272 属性.方法开发:http://blog.csdn.net/waxgourd0/article/details/7652478 但是由于我的目的是开发一个身份证识别仪的ActiveX控件,因此我就要先仿照识别仪ActiveX开发一个Ac