標籤:
前言
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 {@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.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)