Dialog主题Activity保持背景亮度
<item name="android:backgroundDimEnabled">false</item>(在style中设置)
-------------------------------------------------------------------------------------------------------------------------
Dialog主题Activity设置透明背景
<item name="android:windowBackground">@drawable/bgcolor</item>(在style中设置)
新建drawable/bgcolor.xml文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#0000" /><!-- 设置透明 -->
<stroke android:width="3dp" android:color="#0000" /><!-- 设置透明 -->
<corners android:radius="3dp" />
<padding android:left="3dp" android:top="3dp" android:right="3dp"
android:bottom="3dp" />
</shape>
-------------------------------------------------------------------------------------------------------------------------
实现再按一次退出程序
Exit exit = new Exit();
// ...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
pressAgainExit();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* 再按一次退出程序。
*/
private void pressAgainExit() {
if (exit.isExit()) {
finish();
} else {
Toast.makeText(getApplicationContext(), "再按一次退出程序", 1000).show();
exit.doExitInOneSecond();
}
}
class Exit {
private boolean isExit = false;
private final Runnable task = new Runnable() {
@Override
public void run() {
isExit = false;
}
};
public void doExitInOneSecond() {
isExit = true;
HandlerThread thread = new HandlerThread("doTask");
thread.start();
new Handler(thread.getLooper()).postDelayed(task, 2000);
}
public boolean isExit() {
return isExit;
}
public void setExit(boolean isExit) {
this.isExit = isExit;
}
}
-------------------------------------------------------------------------------------------------------------------------
数据存储之SharePreferences
SharedPreferences settings = getSharedPreferences("savesetting", 0);//设置保存字段的xml文件
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dateMode", true);//赋值----字段名为dataMode的值为true(如果是赋值给String类型,则为putString,依此类推)
// Commit the edits!
editor.commit();//保存
*******注意,在程序运行之后会生成该文件(savesetting.xml)*******
settings.getBoolean("dataMode",false);//dataMode为要获取的字段,false为默认值(当dataMode字段不存在时的返回值)
-------------------------------------------------------------------------------------------------------------------------
EditText设置/隐藏光标位置、选中文本和获取/清除焦点
1. 设置光标到指定位置(当内容过多时,可通过设置光标位置来让该位置的内容显示在屏幕上)
editText.setSelection(2);
2. 隐藏光标
editText.setCursorVisible(false);
3. 点击全选文本(不用放到监听器)
editText.setSelectAllOnFocus(true);
4. 获取和失去焦点
editText.requestFocus();//请求获取焦点
editText.clearFocus();//清除焦点
-------------------------------------------------------------------------------------------------------------------------
WebView使用方法及按钮滚动控制网页(需要设置INTERNET权限)
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
editText.setText(url);
return true;
}
});
webView.setOnTouchListener(new webViewListener());
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webView.loadUrl("http://www.baidu.com");
设置滚动(以下加入到监听器中就ok,具体跳转位置可自行设置)
webView.setScrollY(0);//跳转到网页顶端
webView.setScrollY((int) (webView.getContentHeight() * webView.getScale() - (webView.getHeight() +webView.getScrollY())));//跳转到网页底端
WebSettings webSettings =webView.getSettings();
webSettings.setJavaScriptEnabled(true);//设置支持javascript
webSettings.setAllowFileAccess(true);//设置支持文件访问
webSettings.setBuiltInZoomControls(true);//设置支持缩放
webSettings.setDisplayZoomControls(false);//设置不显示放大缩小按钮
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);//设置优先级
webSettings.supportMultipleWindows();//设置多窗口
webSettings.setUseWideViewPort(true);//设置自适应屏幕
webSettings.setLoadWithOverviewMode(true);
设置按返回键时webview的响应
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && browser_webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
网页内的右键菜单
- public boolean onLongClick(View view) {
-
- HitTestResult mResult = mWebView.getHitTestResult();
-
- final int type = mResult.getType();
- switch (type) {
- case HitTestResult.ANCHOR_TYPE:
- case HitTestResult.SRC_ANCHOR_TYPE:
-
- break;
-
- case HitTestResult.IMAGE_TYPE:
- case HitTestResult.IMAGE_ANCHOR_TYPE:
- case HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
-
- break;
-
- default:
-
- break;
- }
- return true;
- }
网页内的自由复制
- private void emulateShiftHeld(KeyEvent.Callback view)
- {
- try
- {
- KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
- shiftPressEvent.dispatch(view);
- } catch (Exception e)
- {
- }
- }
出错界面
- new WebViewClient()
- ...此为背景
- @Override
- public void onReceivedError(WebView view, int errorCode,
- String description, String failingUrl) {
- view.stopLoading();
- view.clearView();
-
-
- mWebView.loadUrl("file:///android_asset/error.html");
- }
点外部链接调用自己的浏览器
在manifest.xml里主activity加入intent
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:scheme="http" />
- <data android:scheme="https" />
- <data android:scheme="about" />
- <data android:scheme="javascript" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.BROWSABLE" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:scheme="http" />
- <data android:scheme="https" />
- <data android:scheme="inline" />
- <data android:mimeType="text/html"/>
- <data android:mimeType="text/plain"/>
- <data android:mimeType="application/xhtml+xml"/>
- <data android:mimeType="application/vnd.wap.xhtml+xml"/>
- </intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:scheme="file" />
- </intent-filter>
外部调用就ok了,连file文件都能调用,若自己调用的话
- Uri uri = Uri.parse("file://data/data/test.html");
-
- Intent it = new Intent(Intent.ACTION_VIEW, uri);
- context.startActivity(it);
-------------------------------------------------------------------------------------------------------------------------
使用android studio出现The TaskContainer.add() method has been deprecated and is scheduled to be remove d in Gradle 2.0. Please use the create() method instead.
将cmd.exe复制到D:/xxx/AndroidStudioProjects/webBrowserTestProject(即项目所在根目录下)
输入gradle build回车就可以看到错误信息(p.s.其实只要是android studio提示gradle的问题都可用此命令查看,至少目前我遇到的都行。)
-------------------------------------------------------------------------------------------------------------------------
使用android studio出现pkg: /data/local/tmp/com.example.webbrowsertest
Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]
卸载后重新执行就OK
-------------------------------------------------------------------------------------------------------------------------
识别多点触碰
//用3根手指触碰时退出程序
if (event.getPointerCount() == 3 && event.getAction() == MotionEvent.ACTION_MOVE) {
finish();
}
-------------------------------------------------------------------------------------------------------------------------
去掉标题栏
在setContentView()方法的前面插入代码:
requestWindowFeature(Window.FEATURE_NO_TITLE);
-------------------------------------------------------------------------------------------------------------------------
获取网页html源代码
public class HttpDownloader {
private static URL url = null;
public static String download(String urlPath) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader br = null;
try {
//create a URL object
url = new URL(urlPath);
Log.e("vitest","----1----");
//create http connection
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//use i/o stream to read data
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
while ((line=br.readLine()) != null) {
sb.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Error------","Url Failed ! "+e.getMessage());
}
return sb.toString();
}
}
VI
--------------------------------------
关键之处
---
-------------------
------------VI
在OnCreate中加入下面的代码,不然就无法获取html会报错android.os.NetworkOnMainThreadException
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
-------------------------------------------------------------------------------------------------------------------------
数据库之SQLite
----》 DataBaseOpenHelper.java 继承SQLiteOpenHelper
public class DataBaseOpenHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DICTIONARY_TABLE_NAME = "info";
private static final String KEY_WORD = "name";
private static final String KEY_DEFINITION = "text";
private static final String VARCHAR=" varchar(30) not null";
private static final String ID="id int primary key not null";
private static final String COMMA=",";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +ID+COMMA+
KEY_WORD + VARCHAR +COMMA+
KEY_DEFINITION + VARCHAR+");";
public DataBaseOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public DataBaseOpenHelper(Context context, String name, int version) {
this(context, name, null, version);
}
public DataBaseOpenHelper(Context context, String name) {
this(context, name, VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DICTIONARY_TABLE_CREATE);//create a table
sqLiteDatabase.execSQL(insertData(1,"zzz","zzzzzzz"));//insert data after create the table
sqLiteDatabase.execSQL(insertData(2,"zzz11","'zzzzzzz22"));
sqLiteDatabase.execSQL(insertData(3,"zzz222","'zzzzzzz333"));
Log.i("TestSQLite","create database success!");
}
public String insertData(int id,String name,String text){
String result="insert into "+DICTIONARY_TABLE_NAME+"(id,name,text) values('"+id+"','"+name+"','"+text+"');";
return result;
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
}
}
----》 使用(创建数据库,并连接数据库,将数据库中指定值导入字符串数组)
//create a database named <-dbinfo->
DataBaseOpenHelper dboh = new DataBaseOpenHelper(MainActivity.this, "dbinfo");
//*invoke the dboh to create the database
SQLiteDatabase db = dboh.getWritableDatabase();int countData=0;
Cursor cursor = db.query("info", new String[]{"name", "text"}, null, null, null, null, null);
while (cursor.moveToNext()) {
countData++;
}
String[] name = new String[countData];
String[] text = new String[countData];
int count = 0;
Cursor cursor1 = db.query("info", new String[]{"name", "text"}, null, null, null, null, null);
while (cursor1.moveToNext()) {
name[count] = cursor1.getString(cursor.getColumnIndex("name"));
text[count] = cursor1.getString(cursor.getColumnIndex("text"));
count++;
}
-------------------------------------------------------------------------------------------------------------------------
String resource ID #0x7d
注意赋值类型
-------------------------------------------------------------------------------------------------------------------------
手势使用方法
private GestureDetector gd = new GestureDetector(new GestureDetector.OnGestureListener() {
//--手指在屏幕上移动距离小于此值不会被认为是手势--
private static final int SWIPE_MIN_DISTANCE = 120;
//--手指在屏幕上移动速度小于此值不会被认为手势--
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float v, float v2) {
return false;
}
@Override
public void onLongPress(MotionEvent motionEvent) {
}
//--手势识别函数,到此函数被系统回调时说明系统认为发生了手势事件,--
//--我们可以做进一步判定。--
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//--如果第1个坐标点大于第二个坐标点,说明是向左滑动--
//--滑动距离以及滑动速度是额外判断,可根据实际情况修改。--
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE &&
Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//left
Log.i("GestureDemo", "left");
editText2.setText("left");
return true;
}else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE &&
Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//right
Log.i("GestureDemo", "right");
editText2.setText("right");
return true;
}
return false;
}
});
在需要使用的控件中,设置ontouch监听器
只需一句,return gd.onTouchEvent(motionEvent);就可以实现左右滑动手势
-------------------------------------------------------------------------------------------------------------------------
浮动窗口中响应事件
在布局文件中响应的view中添加
android:clickable="true"
-------------------------------------------------------------------------------------------------------------------------
循环显示图片时使用的简便方法
mCurrentPhotoIndex = (mCurrentPhotoIndex + 1)
% mPhotoIds.length;
-------mCurrentPhotoIndex为当前显示的图片索引-------mPhotoIds为图片int组
-------------------------------------------------------------------------------------------------------------------------
格式化时间
/**
* 格式化时间
* @param dur-8*60*60*1000初始化时间为00:00:00(dur为ms毫秒)
* @return
*/
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm:ss");
Date date=new Date();
public String formatTime(int dur) {
date.setTime(dur-8*60*60*1000);
return simpleDateFormat.format(date);
}
-------------------------------------------------------------------------------------------------------------------------
自定义设置按钮样式
在drawable中新建buttonstyle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/buttonpressed" />
<item android:state_enabled="true" android:drawable="@android:color/holo_blue_bright" />
</selector>
然后设置按钮的background属性为
@drawable/buttonstyle
-------------------------------------------------------------------------------------------------------------------------
动态改变是否全屏
设置全屏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
设置非全屏
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
-------------------------------------------------------------------------------------------------------------------------
重启activity
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
直接调用reload();就Ok啦1
-------------------------------------------------------------------------------------------------------------------------
获取标题栏的高度
com.example.app2改成你的包名
private int getActionBarHeight() {
int actionBarHeight = actionBar.getHeight();
if (actionBarHeight != 0)
return actionBarHeight;
final TypedValue tv = new TypedValue();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
} else if (getTheme().resolveAttribute(com.example.app2.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
return actionBarHeight;
}
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------