android常用方法总结1

来源:互联网 发布:three.js源码 编辑:程序博客网 时间:2024/06/18 09:17

1.隐去标题栏(应用程序的名字)
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
2.隐去状态栏部分(电池等图标和一切修饰部分)
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

注意:以上两行代码要写在setContentView(R.layout.main);上面。
3.得到当前外部存储设备的目录
//SDCARD
SDPATH = Environment.getExternalStorageDirectory() + "/";

4.我要做一个软件,首先是一个Activity里面显示全屏显示一张图片,3秒后跳转到另外一个Activity

第一个activity
public class StartPicActivity extends Activity{

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);
  setContentView(R.layout.picture);
  new CountDownTimer(3000,100) {
   @Override
   public void onTick(long millisUntilFinished) {
    // TODO Auto-generated method stub   
   }
         @Override
         public void onFinish() {    //倒计时结束后在这里实现activity

跳转
          Intent intent = new Intent();                  
          intent.setClass(StartPicActivity.this, Second.class);
          startActivity(intent);
          finish();                  //跳转后销毁自身的activity  否则

按返回 还会跳回到图片
         }
              }.start();
 }
}

法2:
在布局文件里配置就可以,如在main.xml中配置:
<ImageView   
android:layout_width="fill_parent"  

android:layout_height="fill_parent"  
android:src="@drawable/图片名称"/>
在actvity中onCreate方法中代码:   
// 无title       
requestWindowFeature(Window.FEATURE_NO_TITLE);   
// 全屏       
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
三秒跳转到另一个activity可以使用Timer类,或使用Thread.sleap(3000)就可

以,然后startIntent就行

5.弹出对话框的方法:
法1:
AlertDialog.Builder dialog = new AlertDialog.Builder

(ShowActivity.this);

dialog.setTitle("test");
dialog.setMessage("sss?"+"test2:"+"abc");
dialog.setIcon(R.drawable.build1);

final TextView text = new TextView(TestActivity.this);
dialog.setView(text); 
text.setText("干扰时启动可能导致最终轨迹误差较大,建议更换起始点继续行

走!");
text.setTextSize(20);
text.setTextColor(Color.argb(255, 255, 255, 255));

/**
* 设置EditText
*/
final EditText input = new EditText(MainActivity.this);

input.setHint("请输入您的名字...");//显示提示信息
dialog.setView(input);
dialog.setPositiveButton("确定",new DialogInterface.OnClickListener()

{
 @Override
 public void onClick(DialogInterface arg0, int arg1) {
 // TODO Auto-generated method stub
  Toast.makeText

(ShowActivity.this.getApplicationContext(),"你点击了确定按钮!",

1500).show(); 
 });
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()

{
 @Override
 public void onClick(DialogInterface arg0, int arg1)
 {
  // TODO Auto-generated method stub
  Toast.makeText

(ShowActivity.this.getApplicationContext(),"点击了取消按钮!",

1500).show();
 }
 });

dialog.setNeutralButton("center", new DialogInterface.OnClickListener

() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ShowActivity.this.getApplicationContext(),"你点击了中间

按钮!", 1500).show();
   }
  });
dialog.create().show();//dialog.show();
法2:

dialog.setTitle("确认位置信息").setIcon

(android.R.drawable.ic_dialog_info).setMessage("是否确认以此为出发点?

").setPositiveButton("确定",new DialogInterface.OnClickListener() {});

6.传递消息的方法:
Handler myHandler = new Handler()
{
 @Override
 public void handleMessage(Message msg)
 {
  //如果消息来至于子线程
  if(msg.what == 0x123)
  {
   //将读取的内容追加显示在文本框中 

//tv_show.append( msg.obj.toString()+"\n");
  }
 }
};

Message msg = new Message();
msg.what = 0x123;
msg.obj = jsonObj.toString();
myHandler.sendMessage(msg);

 

7.Timer、TimerTask

Timer timer = null;
TimerTask task = null;
timer = new Timer("timer",true);
task = new TimerTask()
{
 @Override
 public void run()
 {
  myHandler.sendEmptyMessage(0x1233);
 }
};
timer.schedule(task, 0, 1200);

if(timer != null)
{
timer.cancel();    
task.cancel();    
timer.purge();    
timer = null;
}
8.加载位图的方法
Bitmap bm = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.flower);

9.设置图片按钮的方法:
ImageButton btnStart = new ImageButton(this);
btnStart.setBackgroundResource(R.drawable.Flower);
Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);//参数不能为0
btnStart.setImageMatrix(matrix);

10.拖动图片(按钮)的方法:
ImageButton btnStart = new ImageButton(this);
btnStart.setBackgroundResource(R.drawable.Flower);

btnStart.getBackground().setAlpha(alphaValue);//设置透明度:0-255

Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);//参数不能为0
btnStart.setImageMatrix(matrix);

btnStart.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event){ 
// TODO Auto-generated method stub
int ea=event.getAction();
Log.i("TAG", "Touch:"+ea);
    
float oriX;
float oriY;
 
switch(ea){
case MotionEvent.ACTION_DOWN:
oriX = event.getRawX();
oriY = event.getRawY();

break;
     
case MotionEvent.ACTION_MOVE:
//根据移动的相对位移得到按钮在Activity中的位置
oriX = event.getRawX();
oriY = event.getRawY();
     
case MotionEvent.ACTION_UP:
    
break;
}
return false;
}});


11.设置按钮长按时响应的事件:
btnStart.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub

AlertDialog.Builder dialog = new AlertDialog.Builder

(MainActivity.this);
    
dialog.setTitle("selection");
dialog.setIcon(android.R.drawable.ic_dialog_info);
dialog.setPositiveButton("ok",new

DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1)
{
// TODO Auto-generated method stub
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//Toast.makeText(ShowActivity.this.getApplicationContext(),"你点击了取消按钮!", 1500).show();
}
});
dialog.create().show();

return false;
}
});

注意:setOnLongClickListener事件发生之前,会有多个setOnTouchListener事件的MotionEvent.ACTION_DOWN被触发!
即如果是轻轻的点击了一下按钮,触发的只是setOnTouchListener事件的MotionEvent.ACTION_DOWN动作被触发!
如果是长按按钮,会先触发setOnTouchListener事件的MotionEvent.ACTION_DOWN动作,该动作被调用了
一次之后,才执行setOnLongClickListener事件中的onLongClick函数!

12.缩放图片
Bitmap bm = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.flower);
Bitmap tmpBm;

Matrix matrix = new Matrix();

float scaleRatio = (float)getResources().getDisplayMetrics().widthPixels/(float)g_width;//注意:强转是必须的!默认返回的屏幕尺寸

为int类型,必须转换成float类型才能获取比例,否则有可能为0,导致在创建缩放位图时异常终止!
//matrix.postScale(scaleRatio, scaleRatio);//方法1:参数不能为0
matrix.setScale(scaleRatio, scaleRatio);//
//方法1:
tmpBm = Bitmap.createBitmap(bm,0,0,bm.getWidth(),bm.getHeight(),matrix,true);//第2、3个参数如果非0可能出错?

//方法2:
tmpBm = Bitmap.createScaledBitmap(bm, MainActivity.dm.widthPixels, (int)(g_height*scaleRatio),true);
 
13.view的方法
AbsoluteLayout layout;
layout = new AbsoluteLayout(this);
//layout.setOrientation(LinearLayout.VERTICAL);
//layout.addView(btnStart);
  
layout.addView(tpView);
layout.addView(btnStart,10,10);
layout.addView(tvPos,320,300);


14.设置哪个Activity为默认的启动主页的方法:
在AndroidManifest.xml中
<application
        android:name="com.example.DemoApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
            android:configChanges="orientation|screenSize"
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category

android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.test.Service" >
         
        </service>
    </application>

15.显示提示信息的方法:
Toast.makeText(MainActivity.this.getApplicationContext(),"你点击了确定按钮!", 1500).show();

16.//获取系统闹钟服务
am_clientSendInfo = (AlarmManager) getSystemService

(Service.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this,TestActivity.class);
pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);

//每隔3s发送一次
am_clientSendInfo.setRepeating(AlarmManager.RTC_WAKEUP, 0, 10000, pi);

17.获取手机IMSI的方法:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imsi = tm .getSubscriberId();

注意:读取该信息需要注册权限信息:
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

 

18.在ImageView子类上进行绘图的方法(通常是继承View的子类并重载OnDraw方法):

重载OnDraw方法。

参考:http://blog.csdn.net/yanzi1225627/article/details/8581840


19.android动态布局呈现

首先要却这个界面的布局,是AbsoluteLayout,RelativeLayout还是其他,然后就可以再里面添加控件了:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//确定界面的布局
AbsoluteLayout abslayout=new AbsoluteLayout (this);
setContentView(abslayout);
//创建一个button按钮
Button btn1 = new Button(this);
btn1.setText(”this is a button”);
btn1.setId(1);
//确定这个控件的大小和位置
AbsoluteLayout.LayoutParams lp1 =
new AbsoluteLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0,100);
abslayout.addView(btn1, lp1 );

}
一个界面可以布置一个布局,可以多个布局一起设计:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//设置界面的布局
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);

//添加一个AbsoluteLayout子布局,并给这个布局添加一个button
AbsoluteLayout abslayout=new AbsoluteLayout (this);
abslayout.setId(11);
Button btn1 = new Button(this);
btn1.setText(”this is a abslayout button”);
btn1.setId(1);
AbsoluteLayout.LayoutParams lp0 = new AbsoluteLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,100,0);
abslayout.addView(btn1, lp0 );
//将这个子布局添加到主布局中
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
relativeLayout.addView(abslayout ,lp1);

//再添加一个子布局
RelativeLayout relativeLayout1 = new RelativeLayout(this);
Button btn2 = new Button(this);
btn2.setText(”this is a relativeLayout1 button”);
btn2.setId(2);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp2.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
relativeLayout1.addView(btn2 ,lp2);

//将这个布局添加到主布局中
RelativeLayout.LayoutParams lp11 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp11.addRule(RelativeLayout.BELOW ,11);
relativeLayout.addView(relativeLayout1 ,lp11);
}

参考:http://zhidao.baidu.com/question/285746423.html

 

20.ACTION_DOWN、ACTION_UP与ACTION_POINTER_DOWN和ACTION_POINTER_UP事件区别:

ACTION_MASK在Android中是应用于多点触摸操作,字面上的意思大概是动作掩码的意思吧。在onTouchEvent(MotionEvent event)中,使用switch

(event.getAction())可以处理ACTION_DOWN和ACTION_UP事件;使用switch

(event.getAction() & MotionEvent.ACTION_MASK)就可以处理处理多点触摸的ACTION_POINTER_DOWN和ACTION_POINTER_UP事件。
ACTION_DOWN和ACTION_UP就是单点触摸屏幕,按下去和放开的操作;

ACTION_POINTER_DOWN和ACTION_POINTER_UP就是多点触摸屏幕,当有一只手指按下去的时候,另一只手指按下和放开的动作捕捉;ACTION_MOVE就是手指在屏幕

上移动的操作;常用的都是这几个吧。

备注:来自于网络

 

21.布局中的宽高属性fill_parent、match_parent、wrap_content

fill_parent 填充整个屏幕。 match_parent_自适应。wrap_content 是更具你的textview里的内容来判断大小。

参考:http://zhidao.baidu.com/question/463015516.html


22.android在代码中实现在布局控件中动态添加控件

布局的layout文件内容:
----------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/linearlayout">

<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<Button android:layout_height="wrap_content" android:id="@+id/add"
android:text="Add" android:layout_width="100px"></Button>
<Button android:layout_height="wrap_content"
android:layout_width="100px" android:text="Remove" android:id="@+id/remove"></Button>
</LinearLayout>
<TextView android:id="@+id/TextView01" android:text="This is textView."
android:layout_width="fill_parent" android:gravity="center"
android:layout_height="50px"></TextView>

</LinearLayout>
----------------------------------------------------------------------------------

对应Activity的内容:
----------------------------------------------------------------------------------
package com.foxconn.dialog;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class DialogTest extends Activity implements OnClickListener {

private Button add_btn, remove_btn;
private LinearLayout linearLayout;
private int index = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
register();
}

private void register() {
add_btn.setOnClickListener(this);
remove_btn.setOnClickListener(this);
}

private void findViews() {
add_btn = (Button) findViewById(R.id.add);
remove_btn = (Button) findViewById(R.id.remove);
linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
}

protected View createView() {
Button btn = new Button(this);
btn.setId(index++);
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setText("aaaaaa" + index);
return btn;
}

private void removeView() {
//获取linearlayout子view的个数
int count = linearLayout.getChildCount();
//研究整个LAYOUT布局,第0位的是含add和remove两个button的layout
//第count-1个是那个文字被置中的textview
//因此,在remove的时候,只能操作的是0<location<count-1这个范围的
//在执行每次remove时,我们从count-2的位置即textview上面的那个控件开始删除~
if (count - 2 > 0) {
//count-2>0用来判断当前linearlayout子view数多于2个,即还有我们点add增加的button
linearLayout.removeViewAt(count - 2);
}
}

public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
linearLayout.addView(createView(), 1);
break;
case R.id.remove:
removeView();
break;
default:
break;
}
}
}
参考自:http://zhidao.baidu.com/question/255392766.html
 

  23.对MainActivity添加双击事件:

package com.example.doubleclickdemo;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.util.Log;import android.view.GestureDetector;import android.view.MotionEvent;import android.view.GestureDetector.OnGestureListener;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnGestureListener{//@Override//protected void onCreate(Bundle savedInstanceState) {//super.onCreate(savedInstanceState);//setContentView(R.layout.activity_main);//}@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;}private LinearLayout main;private TextView viewA;private GestureDetector gestureScanner;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);gestureScanner = new GestureDetector(this);gestureScanner.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {public boolean onDoubleTap(MotionEvent e) {viewA.setText("-" + "onDoubleTap" + "-");Toast.makeText(getApplicationContext(), "onDoubleTap", Toast.LENGTH_SHORT).show();// 双击时产生一次Log.v("test", "onDoubleTap");return false;}public boolean onDoubleTapEvent(MotionEvent e) {// 双击时产生两次Log.v("test", "onDoubleTapEvent");Toast.makeText(getApplicationContext(), "onDoubleTapEvent", Toast.LENGTH_SHORT).show();return false;}public boolean onSingleTapConfirmed(MotionEvent e) {viewA.setText("-" + "onSingleTapConfirmed" + "-");Toast.makeText(getApplicationContext(), "onSingleTapConfirmed", Toast.LENGTH_SHORT).show();// 短快的点击算一次单击Log.v("test", "onSingleTapConfirmed");return false;}});main = new LinearLayout(this);main.setBackgroundColor(Color.GRAY);main.setLayoutParams(new LinearLayout.LayoutParams(320, 480));main.setOrientation(LinearLayout.VERTICAL);viewA = new TextView(this);viewA.setBackgroundColor(Color.YELLOW);viewA.setTextColor(Color.BLACK);viewA.setTextSize(16);viewA.setLayoutParams(new LinearLayout.LayoutParams(500, 500));main.addView(viewA);setContentView(main);}@Overridepublic boolean onTouchEvent(MotionEvent me) {return gestureScanner.onTouchEvent(me);}
//实现接口OnGestureListener必须实现下面的所有方法:@Overridepublic boolean onDown(MotionEvent e) {// viewA.setText("-" + "DOWN" + "-");return true;}@Overridepublic boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) { viewA.setText("-" + "FLING" + "- "+velocityX + "- "+velocityY);Log.v("test", "onFling " + e1.getX() + " " + e2.getX());return true;}@Overridepublic void onLongPress(MotionEvent e) {// viewA.setText("-" + "LONG PRESS" + "-");float x=e.getRawX();float y=e.getRawY();viewA.setText("LONG PRESS:\nx:"+x+"\ny:"+y);}@Overridepublic boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,float distanceY) { viewA.setText("-" + "SCROLL" + "- "+distanceX + "- "+distanceY);Log.v("test", "onScroll " + e1.getX() + " " + e2.getX());return true;}@Overridepublic void onShowPress(MotionEvent e) { viewA.setText("-" + "SHOW PRESS" + "-");}@Overridepublic boolean onSingleTapUp(MotionEvent e) {Log.v("test", "onSingleTapUp"); viewA.setText("-" + "SINGLE TAP UP" + "-");return true;}}

参考:http://zhidao.baidu.com/question/195334943.html

24.Adapter(适配器)就是一个连接器

ListView list2 = (ListView)findViewById(R.id.list2);
//定义一个数组
String[] arr ={"孙悟空" , "猪八戒" , "牛魔王"};
//将数组包装ArrayAdapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this , android.R.layout.simple_list_item_1 , arr);
//为ListView设置Adapter
list2.setAdapter(arrayAdapter);

原创粉丝点击