Android入門

來源:互聯網
上載者:User

標籤:

在學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入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.