现在的位置: 首页 > 综合 > 正文

Android应用小技巧集锦

2013年11月16日 ⁄ 综合 ⁄ 共 8488字 ⁄ 字号 评论关闭

1.退出应用程序:

SysUtil mSysUtil= new SysUtil(BActivity.this);  

mSysUtil.exit(); 

源文档<http://blog.csdn.net/Android_Tutor/archive/2011/03/26/6279843.aspx>

 

2.Toast的用法

Toastmsg = Toast.makeText(Main.this, “Message”, Toast.LENGTH_LONG);

msg.setGravity(Gravity.TOP| Gravity.LEFT, msg.getXOffset() / 2, msg.getYOffset() / 2);

msg.show();

源文档<http://hi.baidu.com/telentqq/blog/item/81b3603021fcaf365ab5f576.html>

 

3.路径获取:

System.getProperty("user.dir")

this.getClass().getResource("/")

this.getClass().getResource("")

 

4.相关函数参数详解:

4.0.onItemClick(AdapterView<?> arg0, View view, int arg2,long arg3)函数详解:

AdapterView<?>arg0代表向spinner中加载的一系列字符串,是一个适配器,是字符串和Spinner之间

的桥梁。而view代表Spinner,intarg2代表ItemId, long arg3代表Item的position。

 

4.1.public  View getView(int position, ViewconvertView, ViewGroupparent)函数详解:

//position 就是位置从 0 开始,convertView 是 Spinner,ListView中每一项要显示的 view

//通常return  的 view 也就是 convertView

//parent就是父窗体了,也就是 Spinner,ListView,GridView

 

4.2 voidandroid.widget.PopupWindow.showAtLocation(View parent, int gravity, int x, inty);

PopupWindowmPop;

mPop.showAtLocation((View)v.getParent(), Gravity.TOP | Gravity.LEFT, 252, 50);

//以上面一句为例:第一个参数是指PopupWindow显示在哪一个View之上.后面三个参数控制PopupWindow显

//示的位置,此处表明PopupWindow显示在距左上角x252个像素,y50个像素.

 

5.Activity动态加载View

1getWindow().setContentView(LayoutInflater.from(this).inflate(R.layout.main,null));

2getWindow().setContentView(getLayoutInflater().inflate(R.layout.main,null));

3View view =LayoutInflater.from(this).inflate(R.layout.main,
null);

      setContentView(view);

//等价于setContentView(R.layout.main); 

 

6.得到当前文件、类、方法名、行号:

Thread.currentThread().getStackTrace()[1].getMethodName();

Thread.currentThread().getStackTrace()[1].getLineNumber();

Thread.currentThread().getStackTrace()[1].getClassName();

Thread.currentThread().getStackTrace()[1].getFileName();

Thread.currentThread().getStackTrace()[1].getClass();

Thread.currentThread().getStackTrace()[1].toString(); 

Thread.currentThread().getStackTrace().length;

 

7.启动服务与广播

//启动自定义的服务

Intentit = new Intent(MainActivity.this, MyService.class);

ComponentNamen = MainActivity.this.startService(it);

 

//启动一广播接收器

finalString acction = "com.surekam.broadcast.action.RecAction";

IntentitRecevier = new Intent(acction);

sendBroadcast(itRecevier);

 

8.Activity界面设置

//
强制设置为横屏

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

或:android:screenOrientation="portrait"

 

// 设置为全屏

a.代码实现方式:

@Override

public voidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // hide titlebar of application

    // must be before setting the layout

   
requestWindowFeature(Window.FEATURE_NO_TITLE);

    // hide statusbar of Android

    // could also be done later

   
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

           WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.main);

}

 

b.XML中注册实现方式:

<activityandroid:name=".Convert"

  android:label="@string/app_name"

 
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

<intent-filter>

<actionandroid:name="android.intent.action.MAIN" />

<categoryandroid:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

 

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

源文档 <http://dev.10086.cn/cmdn/wiki/index.php?doc-view-6329.html>

 

<supports-screens

android:largeScreens="true"

android:normalScreens="true"

android:smallScreens="true"

android:anyDensity="true"/>

源文档 <http://www.cnblogs.com/resound/archive/2010/12/13/1904613.html>

 

// 设置在不同屏幕尺寸手机上实现全屏minSdkVersion至少设置为3以上)

在AndroidManifest.xml中添加一条<uses-sdkandroid:minSdkVersion="4" />

 

9.获取手机的品牌

android.os.Build.MODEL                

// 产品型号

android.os.Build.VERSION.SDK        

// SDK版本号

android.os.Build.VERSION.RELEASE        

// 系统版本号

 

10.获得屏幕的宽和高

WindowManager android.app.Activity.getWindowManager()

WindowManagerwindowManager = getWindowManager();

Display display =windowManager.getDefaultDisplay();

int screenWidth =display.getWidth();

int screenHeight =display.getHeight();

 

//判断手机屏幕的方向

DisplayMetrics dm =new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

width=dm.widthPixels;

heigh=dm.heightPixels;

if(width/heigh>0){

//横屏

path= bundle.getString("widthurl");

}

if(width/heigh==0){

//竖屏

path= bundle.getString("heighturl");

}

 

11.禁止黑屏进入省电模式

//此要加入到setContentview(R.layout.xx)前面。

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

 

12.得到SDCard目录的路径

String SDPATH =Environment.getExternalStorageDirectory() + "/";

 

13.调用系统网络设置界面

Intent netSetIntent= new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);

context.startActivity(netSetIntent);

 

14.将软键盘隐藏

//如果在按menu按钮的时候,以及打开了软键盘,则将软键盘隐藏

if(((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).isActive()) {

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).

hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

}

 

15.设置对话框大小

AlertDialog dialog =new AlertDialog.Builder(this).create();

dialog.show();

WindowManager.LayoutParamsparams = dialog.getWindow().getAttributes();

params.width = 200;

params.height = 200;

dialog.getWindow().setAttributes(params);

dialog.getWindow().setContentView(R.layout.main);

//设置对话框中布局按钮的事件

Button bt = (Button)dialog.findViewById(R.id.button2);

bt.setOnClickListener(null);

 

15.画图Paint

Paint p = newPaint();

p.setAntiAlias(true);

p.setTextSize(10);

p.setFakeBoldText(true);//伪粗体,中文使用

p.setTextAlign(Align.CENTER);

p.setShader(labelShader);

p.setAntiAlias(true);//抗锯齿开启

 

16.三态布局

<selectorxmlns:android="http://schemas.android.com/apk/res/android">

<item

android:state_pressed="true"

android:drawable="@drawable/button2_down"/>

<item

android:state_focused="true"

android:state_enabled="true"

android:drawable="@drawable/button2_over"/>

<item

android:state_enabled="true"

android:drawable="@drawable/button2"/>

</selector>

 

17.广播的动态注册与反注册

MyBroadcastmyBroadcast = new RecFileBroadcast();

StringACTION_MYBROADCAST = "android.action.mybroadcast";

IntentFiltermyIntentFilter = new IntentFilter(StaticConstant.ACTION_RECEIVE_FILE);

 

Activity.java文件中:

@Override

protected voidonResume() {

registerReceiver(myBroadcast,myIntentFilter);

}

 

@Override

protected voidonPause() {

unregisterReceiver(myBroadcast);

}

 

18.PopupWindow弹出窗口

--------------------------------------------------------------------------------------------

//获取自定义布局文件popup.xml的视图

View v =getLayoutInflater().inflate(R.layout.main,

null,false);

// 创建PopupWindow实例

PopupWindow popup =new PopupWindow(v, 600, 160, true);

--------------------------------------------------------------------------------------------

TextView tt = newTextView(this);

tt.setText("Howsdfsdfsdllsdfsdf\njava\nCC++\n!!");

tt.setTextColor(Color.RED);

tt.setBackgroundColor(Color.WHITE);

PopupWindow
pw = new PopupWindow(tt,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

tt.setOnClickListener(newOnClickListener() {

 

@Override

publicvoid onClick(View v) {

pw.dismiss();

}

});

if (!pw.isShowing())

pw.showAsDropDown(findViewById(R.id.button4),20,10);

Toast.makeText(MainUI.this,"Btn 4000....", 2000).show();

 

19.绘图时得到文本的长度与高度

float[]widths=newfloat[text.length()];

int width =m_txtPaint.getTextWidths(text, widths);

 

Rect rect = newRect();             

txtPaint.getTextBounds(text,0, text.length(), rect);

intwidth=rect.width();

 

int height =Math.abs((int)(m_txtPaint.getFontMetrics().descent -m_txtPaint.getFontMetrics().ascent));

 

20.重设布局中控件或布局的宽高

LinearLayout view =(LinearLayout) findViewById(R.id.layout);

LayoutParams params = view.getLayoutParams(); 
//得到布局参数

params.height= 100; 
//得到高

params.width= 50; 
//得到宽

view.invalidate();
  //更新视图

源文档 <http://gundumw100.iteye.com/blog/1181990>

 

21.画虚线

PathEffect effects =new DashPathEffect(new float[]{5,5,5,5},1);

源文档 <http://blog.csdn.net/linweidong/article/details/5888016>

 

22.具有边框背景

02-2.3-/drawable-mdpi/bg_border.xml

<shape>

<solidandroid:color="#000000"/>

<strokeandroid:width="2dip" android:color="#FF0000"/>

</shape>

 

23.
Padding 与 margin 区别

padding填充的意思,指的是view中的content与view边缘的距离

margin一般用来描述控件间位置关系,而padding一般描述控件内容和控件的位置关系。

padding类似文本中的indent(缩进),而margin表示的是view的左边缘与parentview的左边缘的距离

 

gravity与layout_gravity的区别

android:gravity用于设置View组件的对齐方式,而android:layout_gravity用于设置Content的对齐方式。

源文档 <http://androidstudy.iteye.com/blog/780135>

 

24.检查sd卡是否存在

private booleancheckSdcard() {

//如果sd卡存在,则返回true

if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){

returntrue;

}else{

returnfalse;

}

}

 

25.voidcom.surekam.view.GLRender.onDrawFrame(GL10 gl)

1.setRenderMode(RENDERMODE_WHEN_DIRTY);

2. 需要刷新时,调用requestRender()函数即可;

源文档 <http://www.eoeandroid.com/thread-93767-1-1.html>

GLSurfaceView glView= new GLSurfaceView(context);

glView.setRenderer(newGLRender(context));

glView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY| GLSurfaceView.RENDERMODE_WHEN_DIRTY);

glView.requestRender();

注:setRenderMode()需在setRenderer()后调用;

 

以后持续更新。。。

【上篇】
【下篇】

抱歉!评论已关闭.