標籤:
在學Android,摘自《第一行代碼——Android》
布局管理
通過xml檔案進行布局管理。
android:id="@+id/button_1" 為當前的元素定義一個唯一識別碼,@+id用於定義,@id用於引用;android:text 為其上內容;android:layout_width和android_height控制其寬度和高度
setContentView()
載入布局,傳入一個布局檔案的id。如setContentView(R.layout.first_layout)
在AndroidManifest檔案中註冊
活動的註冊聲明要放在<application>標籤內,通過<activity>標籤來對活動進行註冊的。使用android:name來指定具體註冊哪一個活動,使用android:label指定活動中標題列的內容。若要讓某活動作為程式的主活動,則需加入<action android:name="android.intent.action.MAIN" />和<category android:name="android.intent.category.LAUNCHER" />。
沒有主活動的程式一般作為第三方服務供其他的應用在內部進行調用。
隱藏標題列
在setContentView()之前加入requestWindowFeature(Window.FEATURE_NO_TITLE)
按鈕的設定
Button button1 = (Button) findViewById(R.id.button_1); //通過定義好的R.id.button_1產生Button對象。findViewById()返回View對象
活動中的菜單
建立./res/menu,在其下設定Android XML File檔案。通過<item>標籤建立功能表項目(android:id給功能表項目指定一個唯一識別碼,android:title給功能表項目指定一個名稱)
通過getMenuInflater().inflate(a,b)給當前活動建立菜單,第一個參數用於指定通過哪一個資源檔建立菜單,第二個參數用於指定我們的功能表項目將添加到哪一個Menu對象當中,返回true(public boolean onCreateOptionsMenu(Menu)),表示允許建立的菜單顯示出來。
銷毀活動
finish(),效果和按下Back鍵相同
使用Intent在活動之間穿梭
Intent的用法分為顯式Intent和隱式Intent。
顯式:第一個參數為上下文,第二個參數為目標活動
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
隱式:指定一系列更為抽象的action(指明當前活動可以響應的action)和category(附加資訊)等資訊,交由系統去分析這個Intent,並幫我們找出合適的活動去啟動。通過在(AndroidManifest中)<activity>標籤下配置<intent-filter>的內容,可以指定當前活動能夠響應的action和category。只有<action>和<category>中的內容同時能夠匹配上Intent中指定的action和category時,這個活動才能響應該Intent。每個Intent中只能指定一個action,但能指定多個category。
AndroidManifest.xml
<activity android:name=".SecondActivity" >
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT />
</intent-filter>
</activity>
FirstActivity.java
Intent intent = new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);
使用隱式Intent,可以啟動其他程式的活動
活動之間傳遞資料
向下傳遞資料:父活動intent.putExtra(,),第一個參數為鍵,第二個參數為值。
子活動:Intent intent = getIntent(); //擷取到用於啟動該活動的Intent
String str = intent.getStringExtra(); //參數為鍵
向上傳遞資料:父活動startActivityForResult(intent, )第二個參數為請求碼
子活動: 調用setResult(,)第一個參數用於向上一個活動返回處理結果,一般只使用RESULT_OK和RESULT_CANCELED,第二個參數傳遞資料
因此在父活動中要加入onActivityResult()得到返回的資料
當用back返回時,可以重寫onBackPressed(){}
Android入門