Android開發學習經驗總結

碼頭工人 9年前發布 | 21K 次閱讀 Android 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的情況

 本文由用戶 碼頭工人 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!