码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-08-03 08:59:08      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:


前言


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. 运行一下, 效果如下:
技术分享


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

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

标签:

原文地址:http://blog.csdn.net/oscar999/article/details/47024799

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!