Android ToolBar
ToolBar是在安卓5.0中引入的(android.widget.Toolbar)。在不引入兼容庫的情况下,只能在5.0以上的版本運行;而在引用android.support.v7.widget.Toolbar類之後,可以支持安卓2.1以上版本。
引入了android.support.v7兼容庫。
//build.gradle
compile 'com.android.support:appcompat-v7:25.3.0'
然後更改Application的主题,找到values文件夾下的styles.xml,更改主题為NoActionBar
<!--AndroidManifest.xml-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme
<!--修改AppTheme的定义-->
>
<!--styles.xml-->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
Layout布置
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.zxm.learnactionbartoolbar.MainActivity"
>
<android.support.v7.widget.Toolbar
android:id="@+id/ToolBar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleTextColor="@android:color/white"
android:background="?attr/colorPrimary"
></android.support.v7.widget.Toolbar>
</RelativeLayout>
在res文件夾下新建menu文件夾,然後在该文件夾下新增一个布局文件
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/mySearch"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="ifRoom"
android:title="Search">
</item>
<item
android:id="@+id/myMore"
android:icon="@android:drawable/ic_menu_more"
app:showAsAction="ifRoom|withText"
android:title="More">
</item>
</menu>
Activity Toolbar Code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener{
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.ToolBar);
toolbar.setNavigationIcon(R.mipmap.ic_launcher);
toolbar.setLogo(R.mipmap.ic_launcher);
toolbar.setTitle("ToolBar");
toolbar.setSubtitle("toolbar");
setSupportActionBar(toolbar);
toolbar.setOnMenuItemClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,toolbar.getMenu());
return true;
}
}
顯示Back圖示
toolbar = (Toolbar) findViewById(R.id.hack_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//do something you want
}
});
2017年12月14日
2017年9月24日
ViewTreeObserver
ViewTreeObserver
ViewTreeObserver vto =textViewLeft.getViewTreeObserver();vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < 16) { textViewLeft.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { textViewLeft.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }});
2017年5月8日
Android Dialog 標題換行
Android Dialog 標題換行
TextView view = new TextView(this);view.setText(appraisal.getTitle() + "\n" + appraisal.getNoticeInfo());view.setPadding(40, 20, 0, 20);view.setTextSize(12); Dialog alertDialog = new AlertDialog.Builder(this).setCustomTitle(view);
2017年3月11日
Android 判斷手機或是平板
Android 判斷手機或是平板
public static boolean isPad(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
回傳true就是平板
回傳false就是手機
public static boolean isPad(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
回傳true就是平板
回傳false就是手機
2017年1月7日
Android get StatusBar Height and ActionBar Height
//取得狀態列高度
int statusBarHeight = 0; int resource = this.getResources().getIdentifier("status_bar_height",
"dimen", "android"); if (resource > 0) { statusBarHeight = this.getResources().getDimensionPixelSize(resource); }
//取得標題列高度
int actionBarHeight=0; TypedValue tv = new TypedValue(); if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
getResources().getDisplayMetrics()); }
//應用區域高度
Rect outRect1 = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
//VIEW繪製區域高度
Rect outRect2 = new Rect();
getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect2);
2016年11月25日
Android 禁止螢幕旋轉
Android 禁止螢幕旋轉
AndroidManifest.xml設置
android:screenOrientation="portrait" (強制直向)
android:screenOrientation="landscape" (強制橫向)
Java Code設置
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//畫面直向
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//畫面橫向
以上畫面只要轉方向時,activity 會重新執行。
1、如果不要 activity 重新執行,需要在 AndroidManifest.xml 檔案中,在 activity 加入 android:configChanges="orientation|keyboardHidden" 就會禁止重新執行。
這個屬性指的是,當後邊屬性值代表的事件發生時,Activity 會執行某個函數,orientation 指的是當螢幕旋轉時,keyboardHidden 指的是鍵盤輔助功能改變。“|”為或符號,指這兩個中任意一個發生,就執行 Activity 某個函數。
如果你的開發 API 等級等於或高於 13,你還需要設置 screenSize,因為 screenSize 會在螢幕旋轉時改變。
2、在對應 Activity 中重寫 onConfigurationChanged() 方法:
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 什麼都不用寫
}
else {
// 什麼都不用寫
}
}
如果在 if、else 中,使用了 setContentView(R.layout.xxxx) 函數,那麼就可以實現:每次螢幕旋轉時,調用不同的佈局。
3、動態更改螢幕方向:
在程式中有需要的時候旋轉螢幕,例如
@Override
public void onClick(View v) {
// 如果是豎排,則改為橫向
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// 如果是橫排,則改為直向
else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
重點就是:getRequestedOrientation() 函數、setRequestedOrientation() 函數的使用。
注意:使用這種方法,必須事先在 AndroidManifest.xml 的 <activity> </activity> 中,添加android:screenOrientation 屬性值,不然 getRequestedOrientation() 可能會出問題。
AndroidManifest.xml設置
android:screenOrientation="portrait" (強制直向)
android:screenOrientation="landscape" (強制橫向)
Java Code設置
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//畫面直向
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//畫面橫向
以上畫面只要轉方向時,activity 會重新執行。
1、如果不要 activity 重新執行,需要在 AndroidManifest.xml 檔案中,在 activity 加入 android:configChanges="orientation|keyboardHidden" 就會禁止重新執行。
這個屬性指的是,當後邊屬性值代表的事件發生時,Activity 會執行某個函數,orientation 指的是當螢幕旋轉時,keyboardHidden 指的是鍵盤輔助功能改變。“|”為或符號,指這兩個中任意一個發生,就執行 Activity 某個函數。
如果你的開發 API 等級等於或高於 13,你還需要設置 screenSize,因為 screenSize 會在螢幕旋轉時改變。
2、在對應 Activity 中重寫 onConfigurationChanged() 方法:
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 什麼都不用寫
}
else {
// 什麼都不用寫
}
}
如果在 if、else 中,使用了 setContentView(R.layout.xxxx) 函數,那麼就可以實現:每次螢幕旋轉時,調用不同的佈局。
3、動態更改螢幕方向:
在程式中有需要的時候旋轉螢幕,例如
@Override
public void onClick(View v) {
// 如果是豎排,則改為橫向
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// 如果是橫排,則改為直向
else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
重點就是:getRequestedOrientation() 函數、setRequestedOrientation() 函數的使用。
注意:使用這種方法,必須事先在 AndroidManifest.xml 的 <activity> </activity> 中,添加android:screenOrientation 屬性值,不然 getRequestedOrientation() 可能會出問題。
2016年11月23日
Android Intent用法
Android Intent用法
顯示網頁
Uri uri = Uri.parse("http://google.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
使用郵件MAIL
//傳送文字
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress@emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
//傳送影音附件檔
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/mysong.mp3"));
it.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//傳送圖片附件檔
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/mypic.jpg"));
it.setType("image/jpeg");
startActivity(Intent.createChooser(it, "Choose Email Client"));
撥打電話
//叫出撥號程式
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
//直接打電話出去
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_CALL, uri);
startActivity(it);
//用這個,要在 AndroidManifest.xml 中,加上
//<uses-permission id="android.permission.CALL_PHONE" />
顯示聯絡人清單
Intent it = new Intent(Intent.ACTION_VIEW, People.CONTENT_URI);
startActivity(it);
播放多媒體
Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/song.mp3");
it.setDataAndType(uri, "audio/mp3");
startActivity(it);
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
安裝 APK 檔
Uri uri = Uri.parse("url_of_apk_file");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setData(uri);
it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
it.setClassName("com.android.packageinstaller",
"com.android.packageinstaller.PackageInstallerActivity");
startActivity(it);
//make sure the url_of_apk_file is readable for all users
顯示網頁
Uri uri = Uri.parse("http://google.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
使用郵件MAIL
//傳送文字
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress@emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
//傳送影音附件檔
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/mysong.mp3"));
it.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//傳送圖片附件檔
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/mypic.jpg"));
it.setType("image/jpeg");
startActivity(Intent.createChooser(it, "Choose Email Client"));
撥打電話
//叫出撥號程式
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
//直接打電話出去
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_CALL, uri);
startActivity(it);
//用這個,要在 AndroidManifest.xml 中,加上
//<uses-permission id="android.permission.CALL_PHONE" />
顯示聯絡人清單
Intent it = new Intent(Intent.ACTION_VIEW, People.CONTENT_URI);
startActivity(it);
播放多媒體
Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/song.mp3");
it.setDataAndType(uri, "audio/mp3");
startActivity(it);
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
安裝 APK 檔
Uri uri = Uri.parse("url_of_apk_file");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setData(uri);
it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
it.setClassName("com.android.packageinstaller",
"com.android.packageinstaller.PackageInstallerActivity");
startActivity(it);
//make sure the url_of_apk_file is readable for all users
2016年11月19日
Android 常用系統預設文字大小以及顏色
Android 常用系統預設文字大小以及顏色
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
android:textAppearance="?android:attr/textAppearanceLarge" 或是
sytle="?android:attr/textAppearanceLarge" 實際上是一樣的。
文字大小
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textAppearance="?android:attr/textAppearanceSmall"
字體顏色
android:textColor="?android:attr/textColorPrimary"
android:textColor="?android:attr/textColorSecondary"
android:textColor="?android:attr/textColorTertiary"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textColor="?android:attr/textColorSecondaryInverse"
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
android:textAppearance="?android:attr/textAppearanceLarge" 或是
sytle="?android:attr/textAppearanceLarge" 實際上是一樣的。
文字大小
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textAppearance="?android:attr/textAppearanceSmall"
字體顏色
android:textColor="?android:attr/textColorPrimary"
android:textColor="?android:attr/textColorSecondary"
android:textColor="?android:attr/textColorTertiary"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textColor="?android:attr/textColorSecondaryInverse"
2016年11月7日
Android AlertDialog
Android AlertDialog
建立AlertDialog對話盒
AlertDialog.Builder builder = new AlertDialog.Builder(gameViewA.getContext());
builder.setTitle("抬頭訊息...");
builder.setMessage("本文訊息");
builder.setNegativeButton("右邊按鈕", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNeutralButton("中間按鈕", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setPositiveButton("左邊按鈕", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
建立AlertDialog對話盒
AlertDialog.Builder builder = new AlertDialog.Builder(gameViewA.getContext());
builder.setTitle("抬頭訊息...");
builder.setMessage("本文訊息");
builder.setNegativeButton("右邊按鈕", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNeutralButton("中間按鈕", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setPositiveButton("左邊按鈕", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
2016年11月6日
Android SensorManager Accuracy Value
Android SensorManager Accuracy Value
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
int accuracy
int SENSOR_STATUS_ACCURACY_HIGH
This sensor is reporting data with maximum accuracy
Constant Value: 3 (0x00000003)
int SENSOR_STATUS_ACCURACY_LOW
This sensor is reporting data with low accuracy, calibration with the environment is needed
Constant Value: 1 (0x00000001)
int SENSOR_STATUS_ACCURACY_MEDIUM
This sensor is reporting data with an average level of accuracy, calibration with the environment may improve the readings
Constant Value: 2 (0x00000002)
int SENSOR_STATUS_NO_CONTACT
The values returned by this sensor cannot be trusted because the sensor had no contact with what it was measuring (for example, the heart rate monitor is not in contact with the user).
Constant Value: -1 (0xffffffff)
int SENSOR_STATUS_UNRELIABLE
The values returned by this sensor cannot be trusted, calibration is needed or the environment doesn't allow readings
Constant Value: 0 (0x00000000)
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
int accuracy
int SENSOR_STATUS_ACCURACY_HIGH
This sensor is reporting data with maximum accuracy
Constant Value: 3 (0x00000003)
int SENSOR_STATUS_ACCURACY_LOW
This sensor is reporting data with low accuracy, calibration with the environment is needed
Constant Value: 1 (0x00000001)
int SENSOR_STATUS_ACCURACY_MEDIUM
This sensor is reporting data with an average level of accuracy, calibration with the environment may improve the readings
Constant Value: 2 (0x00000002)
int SENSOR_STATUS_NO_CONTACT
The values returned by this sensor cannot be trusted because the sensor had no contact with what it was measuring (for example, the heart rate monitor is not in contact with the user).
Constant Value: -1 (0xffffffff)
int SENSOR_STATUS_UNRELIABLE
The values returned by this sensor cannot be trusted, calibration is needed or the environment doesn't allow readings
Constant Value: 0 (0x00000000)
2016年10月27日
Android view setVisibility():
Android view setVisibility():
有三個參數:Parameters: visibility One of VISIBLE , INVISIBLE , GONE,
對應的常量值:0、4、8
VISIBLE:0 意思是可見的
INVISIBILITY:4 意思是不可見的,但還佔著原來的空間
GONE:8 意思是不可見的,不佔用原來的佈局空間
View Code
LinearLayout num_Layout = (LinearLayout) findViewById(R.id.num_layout);
if (numberOfRecord > 0){
TextView num = (TextView) findViewById(R.id.num);
num.setText(numberOfRecord.toString() );
num_Layout.setVisibility(0);
}
else {
num_Layout.setVisibility(8);
}
有三個參數:Parameters: visibility One of VISIBLE , INVISIBLE , GONE,
對應的常量值:0、4、8
VISIBLE:0 意思是可見的
INVISIBILITY:4 意思是不可見的,但還佔著原來的空間
GONE:8 意思是不可見的,不佔用原來的佈局空間
View Code
LinearLayout num_Layout = (LinearLayout) findViewById(R.id.num_layout);
if (numberOfRecord > 0){
TextView num = (TextView) findViewById(R.id.num);
num.setText(numberOfRecord.toString() );
num_Layout.setVisibility(0);
}
else {
num_Layout.setVisibility(8);
}
2016年6月13日
Draw SurfaceView from layout xml
Draw SurfaceView from layout xml
Xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView_idd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<jacky.justin.superflashlight.GameViewA
android:id="@+id/surfaceView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</RelativeLayout>
MySurfaceView
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener {
MainActivity mainActivity;
public GameViewA(Context context) {
super(context);
}
public GameViewA(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public GameViewA(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
}
Xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView_idd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<jacky.justin.superflashlight.GameViewA
android:id="@+id/surfaceView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</RelativeLayout>
MySurfaceView
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener {
MainActivity mainActivity;
public GameViewA(Context context) {
super(context);
}
public GameViewA(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public GameViewA(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
}
2015年7月21日
Toast 訊息提示
Toast 訊息提示
Toast.makeText(MainActivity.this, "提示內容",Toast.LENGTH_SHORT ).show();
提示框在顯示之後過了幾秒就會消失,是一種短暫的訊息,可以做為輸入狀況的提示。
Toast.makeText(MainActivity.this, "提示內容",Toast.LENGTH_SHORT ).show();
提示框在顯示之後過了幾秒就會消失,是一種短暫的訊息,可以做為輸入狀況的提示。
AlertDialog 對話框
AlertDialog 對話框
import android.app.AlertDialog;
private void openDialog() {
new AlertDialog.Builder(this)
.setTitle("Google Play Service")
.setMessage("Not Connect !")
.setPositiveButton("Yes"
, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 按下按鈕後執行的動作,無編輯則退出Dialog
}
}).show();
}
import android.app.AlertDialog;
private void openDialog() {
new AlertDialog.Builder(this)
.setTitle("Google Play Service")
.setMessage("Not Connect !")
.setPositiveButton("Yes"
, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 按下按鈕後執行的動作,無編輯則退出Dialog
}
}).show();
}
2015年3月6日
Android 警告信息: tag appears after tag
AndroidManifest.xls
警告信息:<uses-permission> tag appears after <application> tag
解决方法:把<uses-permission> 放到 <application> 前面
警告信息:<uses-permission> tag appears after <application> tag
解决方法:把<uses-permission> 放到 <application> 前面
2014年2月28日
Android onTouch 觸控點
onTouch(View arg0, MotionEvent event)
event.getAction() //獲取觸控動作
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: // 按下
break;
case MotionEvent.ACTION_MOVE: // 拖曳移動
break;
case MotionEvent.ACTION_UP: //離開
break;
}
event.getPointerCount(); //獲取觸控點的數量,比如2則可能是兩個手指同時按壓螢幕
event.getPointerId(nID); //對於每個觸控的點的細節,我們可以通過一個迴圈執行getPointerId方法獲取索引
event.getX(nID); //獲取第nID個觸控點的x位置
event.getY(nID); //獲取第nID個點觸控的y位置
event.getPressure(nID); //LCD可以感應出使用者的手指壓力,當然具體的級別由驅動和物理硬體決定的
event.getDownTime() //按下開始時間
event.getEventTime() // 事件結束時間
event.getEventTime()-event.getDownTime()); //總共按下時花費時間
SoundPool 音效播放
SoundPool soundPool
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
第一個參數 SoundPool 內總共放置的音效數目。
第二個參數 串流類型。
第三個參數 音效品質,預設為1。
音效檔來源設定
soundPool_ID= soundPool.load(mainActivity, R.raw.music01 , 1);
讀取效果音resource的檔案,檔名記得要小寫並且小於1mb
SoundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
soundPool.play(soundPool_ID= , 1.0F, 1.0F, 0, 0, 1.0F);
第一個參數 音效檔來源
第二個參數 左喇叭音量
第三個參數 右喇叭音量
第四個參數 固定用 0
第五個參數 0 為不重複,-1 為無限重複
第六個參數 播放速度,可用 0.5 到 2
SoundPool優點為CPU資源使用率低,反應延遲較少。
用來播放一些短短的音效、急促的效果音很好用。
public void initSounds() {
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// TODO Auto-generated method stub
playSound(1,2);
}
});
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(1, soundPool.load(getContext(), R.raw.gamestart, 1));
}
public void playSound(int sound, int loop) {
Log.e("WelcomeView", "playSound()");
AudioManager mgr = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1.0F);
}
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
第一個參數 SoundPool 內總共放置的音效數目。
第二個參數 串流類型。
第三個參數 音效品質,預設為1。
音效檔來源設定
soundPool_ID= soundPool.load(mainActivity, R.raw.music01 , 1);
讀取效果音resource的檔案,檔名記得要小寫並且小於1mb
SoundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
soundPool.play(soundPool_ID= , 1.0F, 1.0F, 0, 0, 1.0F);
第一個參數 音效檔來源
第二個參數 左喇叭音量
第三個參數 右喇叭音量
第四個參數 固定用 0
第五個參數 0 為不重複,-1 為無限重複
第六個參數 播放速度,可用 0.5 到 2
SoundPool優點為CPU資源使用率低,反應延遲較少。
用來播放一些短短的音效、急促的效果音很好用。
public void initSounds() {
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// TODO Auto-generated method stub
playSound(1,2);
}
});
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(1, soundPool.load(getContext(), R.raw.gamestart, 1));
}
public void playSound(int sound, int loop) {
Log.e("WelcomeView", "playSound()");
AudioManager mgr = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1.0F);
}
2014年2月14日
setRequestedOrientation設定螢幕方向
eclipse Android 設定螢幕方向
模擬器Ctrl+F12切換
Android Code
螢幕的顯示方向會被改變, 要動態修改目前顯示的方向, 可以使用 setRequestedOrientation()
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation參數
系統預設
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
鎖定直式
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
鎖定橫式
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
隨使用者當下
ActivityInfo.SCREEN_ORIENTATION_USER
與活動線程下相同的設定
ActivityInfo.SCREEN_ORIENTATION_BEHIND
不隨SENSOR改變
ActivityInfo.SCREEN_ORIENTATION_NOSENSOR
隨SENSOR改變
ActivityInfo.SCREEN_ORIENTATION_SENSOR
模擬器Ctrl+F12切換
Android Code
螢幕的顯示方向會被改變, 要動態修改目前顯示的方向, 可以使用 setRequestedOrientation()
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation參數
系統預設
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
鎖定直式
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
鎖定橫式
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
隨使用者當下
ActivityInfo.SCREEN_ORIENTATION_USER
與活動線程下相同的設定
ActivityInfo.SCREEN_ORIENTATION_BEHIND
不隨SENSOR改變
ActivityInfo.SCREEN_ORIENTATION_NOSENSOR
隨SENSOR改變
ActivityInfo.SCREEN_ORIENTATION_SENSOR
2014年2月7日
Android無標題列
xml>
在manifest檔中,在需要的Activity元素中加入屬性:
全屏
<activity android:name=".TextButtonActivity" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
無標題列
<activity android:name=".TextButtonActivity" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
Android Code>
全屏
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
無標題列
requestWindowFeature(Window.FEATURE_NO_TITLE);
在manifest檔中,在需要的Activity元素中加入屬性:
全屏
<activity android:name=".TextButtonActivity" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
無標題列
<activity android:name=".TextButtonActivity" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
Android Code>
全屏
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
無標題列
requestWindowFeature(Window.FEATURE_NO_TITLE);
2014年1月12日
LinearLayout
LinearLayout 線性位置版面配置
XML宣告
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
android:layout_gravity="center"
將LinearLayout中的元件置中對齊
android:orientation
屬性值為"horizontal"(水平),所以元件的排版方式是以水平排版呈現
XML宣告
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
android:layout_gravity="center"
將LinearLayout中的元件置中對齊
android:orientation
屬性值為"horizontal"(水平),所以元件的排版方式是以水平排版呈現
訂閱:
文章 (Atom)