Android开发学习经验总结

1.       如何显示与不显示ActionBar ?

如果Activity class 继承的是 Activity , 无法显示ActionBar

已知的必定显示ActionBar的就是 ActionBarActivity

 

代码:

public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.cool_menu,menu);

        return true;

}

1.1       全屏加无状态栏:

requestWindowFeature(Window.FEATURE_NO_TITLE);

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

 

2.       OnTouch 方法中,如果return值设为false,系统检测到这个Touch动作做完反应后,就不会再检查这个状态;如果设为true,就会时时检查,于是可以实现拖动的效果。

3.       灰色的小提示框 Toast

Toast toast = Toast.makeText(this,"不知阁下尊姓大名?",Toast.LENGTH_LONG);

toast.setGravity(Gravity.CENTER,0,0);//设置显示的位置

toast.show();

 

4.       findViewById() 用于查找和关联控件(buttonTextViewImageView 等)

5.       如果要查找Preference中的控件(如,CheckBoxPreferenceEditTextPreference等)用以下方法:

PreferenceManager manager = getPreferenceManager();

CheckBoxPreference password = (EditTextPreference) manager.findPreference("password");

6.       获取Preference中的值使用:

PreferenceManager.getDefaultSharedPreferences(context).getString("user","");

或者分两步,方便查询同一个Preference中的多个值

SharedPreferences sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getBaseContext());

boolean willMusic = sharedPreferences.getBoolean("music",true);

String username = sharedPreferences. getString("user","");

7.       Intent带上附加值Ertra

Intent i = new Intent(CSM_listView.this,ImageViewer.class);

i.putExtra("icon",data.icon);

startActivity(i);

接收方可以接收查看附加数据

int icon = getIntent().getIntExtra("icon",0);

也可以分两步,方便查询多个附加数据

Bundle bundle = getIntent().getExtras();

boolean willContinue = bundle.getBoolean("continueGame",false);

int icon = bundle.getInt ("icon",0);

8.       Intent启动Activity并获取返回值

i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(Intent intent, int requestCode);

并定义对返回值的处理函数

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if(resultCode == RESULT_OK ){ //操作没错误

       Bundle extras = data.getExtras();

       bmp = (Bitmap)extras.get("data");//关键词是“data

       viewPhoto.setImageBitmap(bmp);

     }

}

 

9.       播放音乐

MediaPlayer mp;

mp = MediaPlayer.create(this,R.drawable.fengyanghuagu);

mp.setLooping(true);//循环播放

mp.setVolume(0.3f,0.3f);//设置音量

mp.start();

停止播放并释放占用的资源

mp.stop();

mp.release();

 

10.   对话提示框

10.1 带列表的提示框,点击列表项目启动对应的事件

new AlertDialog.Builder(this).setTitle(R.string.new_game_title)

.setItems(R.array.difficulty, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialoginterface, int i) { //i is the position of item clicked

     startGame(i);

}

}).show();

注释:

/**

                    public void onClick(DialogInterface dialog, int which);

         * This method will be invoked when a button in the dialog is clicked.

         *

         * @param dialog The dialog that received the click.

         * @param which The button that was clicked (e.g.

         *            {@link DialogInterface#BUTTON1}) or the position

         *            of the item clicked.

         */

        /* TODO: Change to use BUTTON_POSITIVE after API council */

10.2 带文本提示和按钮的提示框,点击按钮选择发生的事件

new AlertDialog.Builder(happyNewYear.this).setMessage("想继续游戏吗?").setPositiveButton("继续",new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        Intent i = new Intent(happyNewYear.this,sudugame.class);

                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        i.putExtra("continueGame",true);

                        startActivity(i);

                        finish();

                    }

                }).setNegativeButton("回主菜单",new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        Intent i = new Intent(happyNewYear.this,sudugame.class);

                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        i.putExtra("continueGame",false);

                        startActivity(i);

                        finish();

                    }

                }).show();

10.3  收起Dialog 的 函数

dismiss(); 

11.   防止手机进入休眠状态

PowerManager.WakeLock wl;

wl = pM.newWakeLock(PowerManager.FULL_WAKE_LOCK,"whatever");

wl.acquire();//启动休眠锁

wl.release();//释放休眠锁

 

更多模式参照 http://blog.csdn.net/airk000/article/details/9121003

12.   把较小的数据记录到Preference里方便下次继续,如游戏进度

getPreferences(MODE_PRIVATE).edit().putString(PREF_PUZZLE, toPuzzleString(puzzle)).putString("nochange_record",toPuzzleString(nochange_record)).commit();

//这里存放了两种记录数据,使用syntax sugar哎呦不错

调用存放的数据

puz = getPreferences(MODE_PRIVATE).getString(PREF_PUZZLE, easyPuzzle[0]);

tempNochange = getPreferences(MODE_PRIVATE).getString("nochange_record",emptyStr);

 

13.   关于StringBuilder

StringBuilder buf = new StringBuilder();   //使用StringBuilder制作string(由于要不停地在结尾添加字符,用这个更方便效率更高)

for(int element: puz){

   buf.append(element);

}

  return buf.toString();

 

14.   短时音效的使用(如枪声,按键音)

public SoundPool(int maxStreams, int streamType, int srcQuality)

     * Constructor. Constructs a SoundPool object with the following

     * characteristics:

     *

     * @param maxStreams the maximum number of simultaneous streams for this

     *                   SoundPool object

     * @param streamType the audio stream type as described in AudioManager

     *                   For example, game applications will normally use

     *                   {@link AudioManager#STREAM_MUSIC}.

     * @param srcQuality the sample-rate converter quality. Currently has no

     *                   effect. Use 0 for the default.

     * @return a SoundPool object, or null if creation failed

     * @deprecated use {@link SoundPool.Builder} instead to create and configure a

     *     SoundPool instance

     */

 

public int load(Context context, int resId, int priority)

  * @param context the application context

     * @param resId the resource ID

     * @param priority the priority of the sound. Currently has no effect. Use

     *                 a value of 1 for future compatibility.

     * @return a sound ID. This value can be used to play or unload the sound.

     */

   

 

例子:

SoundPool sp;

int explosion = 0;

sp = new SoundPool(5, AudioManager.STREAM_MUSIC,0);

explosion = sp.load(game, R.raw.mie,1);

sp.setVolume(explosion,1,1);

sp.play(explosion,1,1,0,0,1);//播放

 

 

15.   定义Paint的字体

Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);//反锯齿画笔

foreground.setStyle(Style.FILL);  //充满

foreground.setTextSize(height * 0.75f);  //字体大小

foreground.setTextScaleX(width / height);  //字体高宽比

foreground.setTextAlign(Paint.Align.CENTER);// 字体居格子中间

FontMetrics fm = foreground.getFontMetrics();// Centering in X: use alignment (and X at midpoint)

float x = width / 2;// Centering in Y: measure ascent/descent first

float y = height / 2 - (fm.ascent + fm.descent) / 2;

 

16.   清除之前的Activity stack 记录,使返回键无法返回(用于游戏结束收尾)

Intent i = new Intent(sudu_success.this,happyNewYear.class);

 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

startActivity(i);

finish();

 

17.   画图

  canvas.drawBitmap(happyNY,changeX,changeY,null);

 

18.   延时

try {

     Thread.sleep(1000);

} catch (InterruptedException e) {

     e.printStackTrace();

      }

 

19.   多线程

        Thread sleeper = new Thread(){

            public void run(){

                try {

                    sleep(1200);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

 

            }

        };

        sleeper.start();

        try {

            sleeper.join();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

20.   做混合应用的时候webview 添加JavascriptInterface js掉用方法 出现undefined 调试了一下午终于找到原因:

在绑定的方法前一定要加

@JavascriptInterface

否则在某些手机(比如红米)webview中会出现调用方法时undefined的情况

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。