前言

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" ><Buttonandroid: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 {@Overrideprotected 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();}});}@Overridepublic 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;}@Overridepublic 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 textmTextPaint = new Paint();mTextPaint.setAntiAlias(true);// Must manually scale the desired text size to match screen densitymTextPaint.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// methodmTextPaint.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)*/@Overrideprotected 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 beresult = specSize;} else {// Measure the textresult = (int) mTextPaint.measureText(mText) + getPaddingLeft()+ getPaddingRight();if (specMode == MeasureSpec.AT_MOST) {// Respect AT_MOST value if that was what is called for by// measureSpecresult = 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 beresult = 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// measureSpecresult = 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.MyViewandroid:background="@drawable/red"android:layout_width="fill_parent"android:layout_height="wrap_content"app:text="Red"/><com.oscar999.androidstudy.view.MyViewandroid:background="@drawable/blue"android:layout_width="fill_parent"android:layout_height="wrap_content"app:text="Blue" app:textSize="20sp"/><com.oscar999.androidstudy.view.MyViewandroid:background="@drawable/green"android:layout_width="fill_parent"android:layout_height="wrap_content"app:text="Green" app:textColor="#ffffff"/>  </LinearLayout>

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

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

  1. 【Android从零单排系列十一】《Android视图控件——日历、日期、时间选择控件》

    目录 一.日历.日期.时间组件基本介绍 二.几种常见的控件类型 1.CalendarView –日历控件 2. DatePicker –日期选择控件 3.TimePicker –时间选择控件 4.Ch ...

  2. java 控件内布局_Java开发桌面程序学习(二)————fxml布局与控件学习

    JavaFx项目 新建完项目,我们的项目有三个文件 Main.java 程序入口类,载入界面并显示 Controller.java 事件处理,与fxml绑定 Sample.fxml 界面 sample ...

  3. 用友二次开发 用友控件 Js宿主脚本 调用用友T6 登录 参照 控件示例

    用友二次开发 用友控件 Js宿主脚本 调用用友T6 登录 参照 控件示例 /*****************************************, code by 张朋 ' Email: ...

  4. VB生成二维码图形的控件,CSDN利用盗版卖卖会员44积分赚钱

    VB生成二维码图形的控件+纯VB6生成二维码-无需控件无需DLL-CSDN下载 https://download.csdn.net/download/xiaoyao961/11226174 上面这个是 ...

  5. 鸡啄米之VS2010/MFC编程入门之二十四(常用控件:列表框控件ListBox)

    目录 一.目的: 1.点击列表框某个变量后,编辑框就显示出来这个变量名字 一.参考: 1.VS2010/MFC编程入门之二十四(常用控件:列表框控件ListBox) ①总结:good:亲测有效,适合多 ...

  6. UG/NX二次开发 选择坐标系控件 UF_UI_specify_csys

    文章作者:里海 来源网站:https://blog.csdn.net/WangPaiFeiXingYuan 简介: UG/NX二次开发 选择坐标系控件 UF_UI_specify_csys 与 老函数 ...

  7. Silverlight实用窍门系列:42.读取拖动到控件上的外部txt和jpg文件,多外部文件的拖动【附带实例源码】...

    本实例将读取拖动到Silverlight的ListBox控件中的txt文件或者Jpg文件.在本实例中将讲如果通过UIelementA.Drop事件获取到拖动到UIelementA上的文件的相关名称以及 ...

  8. altas(ajax)控件(二十三):等级选择控件Rating

    一.      简介      等级选择控件Rating提供了一种全新的方式来进行等级选择,在以往的web上我们只能通过使用特殊字符"☆"来表达等级,有了等级选择控件Rating我 ...

  9. [原创]FineUI秘密花园(二十四) — 树控件之数据绑定

    上一篇文章我们介绍了树控件的基本用法,不过都是通过标签来声明树控件的结构,本章我们会详细讲解如何在后台绑定树控件. 绑定到XmlDocument 下面通过一个简单的例子来看如何将XmlDocument ...

最新文章

  1. Spring的Controller是单例还是多例?怎么保证并发的安全
  2. 程序世界的秘密(上)
  3. 转载-如何应对在线故障
  4. 螺旋矩阵 java实现(待消化)
  5. metasploit下载教程linux,Ubuntu下安装Metasploit
  6. 实现socket监听所有网络命名空间
  7. 阿里云香港服务器被攻击进黑洞了怎么办
  8. 基于STC单片机串口扩展网络通信的应用
  9. 【VUE+Elemet 】最全正则验证 + 表单验证 + 注意事项
  10. 一些冷门的JS技巧 顶
  11. codevs 2867 天平系统3
  12. 超全的电商数据指标体系分享,年底数据分析用得上
  13. Mac上如何用自带软件剪切音频(去除多余杂音)?
  14. 微机原理与接口技术:并行接口
  15. 空气压缩机自动控制Multisim仿真
  16. 2021全国人工智能师资培训入高校,百度携手哈工大探索AI师资更多可能
  17. 产品经理基础--04流程图与结构图
  18. SNMP 协议RFC
  19. ORM进阶之Hibernate中关系映射
  20. 专利大战:详解苹果三星矩形设计风波

热门文章

  1. 放肆的使用UIBezierPath和CAShapeLayer画各种图形
  2. 你不懂,仅仅有程序猿懂
  3. Sublime Text 3配置与vim模式(待完整)
  4. 如何利用Pre.im分发iOS测试包
  5. Unity cg vertex and fragment shaders(二)
  6. [转载]Hamachi 安装过程
  7. centos下MySQL Workbench连接时崩溃的解决方法
  8. 混沌思维模型实战课课件分享
  9. 毕马威首次发布《初探元宇宙》报告:从科幻畅想到产业风口(附报告下载链接)...
  10. 2022年引领全球增长的60大技术:机会、增长、投资、洞察