Android的Menu_Dialog----重新認識Android(8)

AND_YOU_with_ME發表於2017-04-14
一、OptionsMenu選項選單(系統選單): 
(一)、簡介:
1、Android應用中的選單預設是隱藏的,只有當使用者點選手機上的MENU鍵,系統才會顯示選單。這種選單叫做選項選單(Option Menu)。
2、從3.0開始,Android不要求手機裝置上必須提供MENU按鍵。因此Android推薦使用ActionBar來代替Menu。
 
(二)、建立選單:(Android提供了兩種建立選單的方式)
1、在java程式碼中建立選單;menu.add("abc");
2、使用xml資原始檔建立選單(res/menu目錄下)。[建議使用]
 
 
(三)、XML資原始檔中定義選單:
1、普通選單:
 <item  選單項
        android:id="@+id/menu_about"
        android:orderInCategory="2"  設定排序順序,小的在前,大的在後
        android:showAsAction="never"   ActionBar的選單項會用到其他值
        android:title="關於"/>         title是必須屬性
 
2、二級選單:
 <item
        android:id="@+id/menu_group2"
        android:orderInCategory="1"
        android:showAsAction="never"
        android:title="設定文字顏色">
        <menu>
            <group>  group可有可無,主要用於對選單項進行批量管理
                <itemandroid:id="@+id/font_red" android:title="red" />
                <item android:id="@+id/font_green" android:title="green"></item>
                <item android:id="@+id/font_blue" android:title="blue"></item>
                <item android:id="@+id/font_yellow" android:title="yellow"></item>
            </group>
        </menu>
    </item>
注意: 要在右上角點選按鈕彈出的選單才能訪問二級選單


(四)、 建立(初始化選項/系統選單)
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);// 用指定的R.menu.main佈局填充Menu物件  res/menu/main.xml
      return true;//如果返回false,選單將不可見
 }
 
(五)、選單操作(點選選單項的響應事件):
@Override
 public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();//獲取被點選選單項的id
  if (id == R.id.action_settings) {//啟動系統設定頁面
   startActivity(new Intent(android.provider.Settings.ACTION_DISPLAY_SETTINGS));//常量字串
   return true;//如果匹配了id,成功處理了選單項點選事件,則返回true.
  }
  return super.onOptionsItemSelected(item);//如果未能處理,則要呼叫父類中的被重寫方法
}
案例:
利用以上定義的xml選單檔案,實現通過選單選項對文字的大小和顏色進行控制。
提示:
設定TextView的字型:tv.setTextSize(float);
修改背景顏色(為紅色/綠色/隨機顏色):tv.setBackgroundColor(Color.rgb(red, green, blue));//0-255
修改字型顏色(為紅色/綠色/隨機顏色):tv.setTextColor(Color.rgb(red, green, blue));
核心程式碼如下:
MainActivity.java
        @Override
        public booleanonOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.font_20:
                        text_main_info.setTextSize(20);
                        break;
                case R.id.font_30:
                        text_main_info.setTextSize(30);
                        break;
                case R.id.font_red:
                        text_main_info.setTextColor(Color.RED);
                        break;
                case R.id.font_green:
                        text_main_info.setTextColor(Color.GREEN);
                        break;
                }
                return super.onOptionsItemSelected(item);
        }
 
二、ContextMenu  上下文選單
(一)、上下文選單介紹:上下文選單繼承自android.view.Menu。
1、上下文選單與Options Menu最大的不同在於
Options Menu的擁有者是Activity,而上下文選單的擁有者是Activity中的View;
每個Activity有且只有一個Options Menu,它為整個Activity服務。而一個Activity往往有多個View,哪個View需要上下文選單就通過Activity的 registerForContextMenu(View view)給這個View註冊上下文選單。
2、生成上下文選單是通過Activity中的onCreateContextMenu()方法:
onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)該方法類似於生成Options Menu的onCreateOptionsMenu(Menu menu)方法;
兩者的不同在於:
onCreateOptionsMenu只在使用者第一次按“Menu”鍵時被呼叫
而onCreateContextMenu會在使用者每一次長按註冊了上下文選單的View時被呼叫。
3、第三個引數ContextMenuInfo 有什麼用呢?
ContextMenuInfo一般用在AdaterViews上(例如:Spinner 、ListView或GridView),它裡面攜帶了AdapterView中的position的資訊
//需要先進行物件造型(向下轉型)
  AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
  int pos = acmi.position;//活動該條目在AdapterView中的位置下標資訊
 
(二)、開發上下文選單的步驟:
1、重寫onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)方法;
2、呼叫Activity的registerForContextMenu(View view)方法為view元件註冊上下文選單;註冊上下文選單後,意味著使用者長按該控制元件後顯示上下文選單。
3、為選單項提供響應,重寫onContextItemSelected(MenuItem item)。[注意區別於上下文選單的onOptionsItemSelected]
(三)、示例程式碼:
 private TextView text_main_info;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text_main_info = (TextView) findViewById(R.id.text_main_info);
        this.registerForContextMenu(text_main_info);//註冊上下文選單到text_main_info元件上
}
 
@Override
public voidonCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // 注意:引用的是menu資原始檔,不是R.id.xx
        getMenuInflater().inflate(R.menu.contextmenu_main, menu);//填充選單
//      可以根據v.getId()來區分哪個元件要顯示上下文選單,根據元件不同,可以顯示不同的上下文選單
menu.add("abc");//在上下文選單的事件處理方法中,可以通過MenuItem物件的getTitle().toString()方法得到,以區分是哪個選單項被點選
menu.add(R.string.hello_world);//利用字串資源新增選單,在res/values/strings.xml中
menu.setHeaderTitle("title....");//設定上下文選單頭部標題
menu.setHeaderIcon(R.drawable.ic_launcher);//設定上下文選單頭部圖示
}
 
@Override
public booleanonContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {//也可以通過item.getTitle()獲取選單項上的字串進行比較
        case R.id.font_20:
                text_main_info.setTextSize(20);
                break;
        case R.id.font_30:
                text_main_info.setTextSize(30);
                break;
        case R.id.font_red:
                text_main_info.setTextColor(Color.RED);
                break;
        case R.id.font_green:
                text_main_info.setTextColor(Color.GREEN);
                break;
        }
        return super.onContextItemSelected(item);
}
AlertDialog ——簡單對話方塊(警告對話方塊)
 父類: android.app.Dialog 
 建立AlertDialog對話方塊的步驟
  1、建立AlertDialog.Builder物件,該物件能建立AlertDialog
Builder是AlertDialog的一個靜態內部類
  2、呼叫Builder物件的方法設定圖示、標題、內容、按鈕等
   setTitle():為對話方塊設定標題
   setIcon ():設定圖示
   setMessage ():設定要顯示的資訊
   setPositiveButton ():設定積極(確定)按鈕(右邊)
   setNegativeButton ():設定消極(取消)按鈕(左邊)
   setNeutralButton ():設定中立按鈕(中間)
  3、呼叫Builder物件的create()方法建立AlertDialog對話方塊
  4、呼叫AlertDialog的show()方法來顯示對話方塊,也可以直接用Builder物件呼叫show()方法
 
當希望使用者點選回退按鈕時,彈出對話方塊,提醒是否真的要退出,應重寫Activity的
onKeyDown(int keyCode, KeyEvent event)方法,判斷是回退按鈕被點選,就彈出提示對話方塊.
if(keyCode==KeyEvent.KEYCODE_BACK){.......}


ProgressDialog——進度對話方塊
 父類: android.app.AlertDialog
 建立 ProgressDialog 對話方塊的步驟
  1.例項化ProgressDialog,建立出ProgressDialog物件
  2.呼叫該物件的方法設定圖示、標題、內容、按鈕等
   setTitle():為對話方塊設定標題
   setIcon ():設定圖示
   setMessage ():設定要顯示的資訊
   setProgressStyle( ):設定進度條的樣式
  3.呼叫 ProgressDialog 物件的show()方法顯示出 ProgressDialog 對話方塊
 
注意:不能阻塞UI執行緒,不能在子執行緒(工作執行緒)中直接操作UI元件!
 
public class ProgressDialogActivity extends Activity{ 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  new MyTask().execute(""); //啟動非同步任務
 }
 class MyTask extendsAsyncTask<String, Integer, Void>{
  private ProgressDialog pd;
  @Override
  protected voidonPreExecute() {
   super.onPreExecute();
   pd = new ProgressDialog(ProgressDialogActivity.this);
   pd.setMax(100);//設定最大進度
   pd.setTitle("title");
   pd.setMessage("message");
   pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//設定水平樣式
   pd.show();
  }
  @Override
  protected VoiddoInBackground(String... params) {
   for(int i = 0;i<100;i+=10){
    publishProgress(i);//通知修改進度
    //禁止在工作執行緒中直接操作ProgressDialog或其他UI元件,因為它們不在同一個執行緒中.
    try {
     Thread.sleep(500);//模擬耗時操作阻塞
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   return null;
  }
  @Override
  protected voidonProgressUpdate(Integer... values) {
   super.onProgressUpdate(values);
   pd.setProgress(values[0]);//更新進度
  }
  @Override
  protected voidonPostExecute(Void result) {
   super.onPostExecute(result);
   pd.dismiss();
  }
 }
}
Toast 吐司
建立吐司的兩種方式:
 1. 通過靜態方法Toast makeText(Context context, int resId, int duration)來建立Toast物件
int resId:R.string.xxx
也可以呼叫過載的方法,傳字串String
注意:只有通過本方法建立的Toast才能setText(...);其他方式建立的Toast不能呼叫setText(...)方法
2. 通過構造方法Toast(Context context)來建立物件
之後再利用下面的方法: 
setView(View view) 設定自定義內容的View,可以是TextView,ImageView等
    案例:建立一個TextView,在裡面設定文字,並把TextView作為此方法的引數
 setGravity(int gravity, int xOffset, int yOffset)  
    設定出現的位置(例如:Gravity.TOP)及X/Y軸的偏移量
    例如: t.setGravity(Gravity.TOP, 0, 0);表示出現在頂部,水平居中.如果沒有呼叫本方法,則預設出現在螢幕中下部居中.
 setMargin(float horizontalMargin, float verticalMargin) 
     設定水平和垂直方向的外邊距,引數為螢幕寬/高的百分比(0.0f~1.0f),為了效果明顯,Toast的內容要簡短一些.
    horizontalMargin The horizontal margin, in percentage of the container width, between the container's edges and the notification
    verticalMargin The vertical margin, in percentage of the container height, between the container's edges and the notification
    例如: t.setMargin(0.2f, 0.4f);//表示從基礎位置向右20%的螢幕寬,再向下40%的螢幕高
 setDuration(int duration) 
    設定顯示的時間:Toast.LENGTH_SHORT(常量值0), Toast.LENGTH_LONG(常量值1)
 show() 
    顯示吐司

相關文章