AndroidTraining學(xué)習(xí)------Building Your First App

Creating an Android Project

  1. app/build.gradle
    Android Studio uses Gradle to compile and build your app. There is a build.gradle file for each module of your project, as well as a build.gradle file for the entire project. Usually, you're only interested in the build.gradle file for the module, in this case the app or application module. This is where your app's build dependencies are set, including the defaultConfig settings:
  • compiledSdkVersion is the platform version against which you will compile your app. By default, this is set to the latest version of Android available in your SDK. By default, this is set to the latest version of Android SDK installed on your development machine. You can still build your app to support older versions, but setting this to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.
  • applicationId is the fully qualified package name for your application that you specified in the New Project wizard.
  • minSdkVersion is the Minimum SDK version you specified during the New Project wizard. This is the earliest version of the Android SDK that your app supports.
  • targetSdkVersion indicates the highest version of Android with which you have tested your application. As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level and thereby take advantage of new platform features.

Running Your App

The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets such as buttons or text fields. ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.

Android provides an XML vocabulary that corresponds to the subclasses of View and ViewGroup so you can define your UI in XML using a hierarchy of UI elements.

Layouts are subclasses of the ViewGroup.

image.png

Figure 1. Illustration of how ViewGroup objects form branches in the layout and contain other View objects.

Create a Linear Layout

  1. From the res/layout/ directory, open the activity_main.xml file.
    This XML file defines the layout of your activity. It contains the default "Hello World" text view.

  2. When you open a layout file, you’re first shown the design editor in the Layout Editor. For this lesson, you work directly with the XML, so click the Text tab to switch to the text editor.

  3. Replace the contents of the file with the following XML:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    </LinearLayout>

LinearLayout is a view group (a subclass of ViewGroup) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of a LinearLayout appears on the screen in the order in which it appears in the XML.

Two other attributes, android:layout_width and android:layout_height, are required for all views in order to specify their size.

Because the LinearLayout is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "match_parent". This value declares that the view should expand its width or height to match the width or height of the parent view.

Add a Text Field

In the activity_main.xml file, within the <LinearLayout> element, add the following <EditText> element:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
</LinearLayout>

Here is a description of the attributes in the <EditText> you added:

  • android:id
    This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
    The at sign (@) is required when you're referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (edit_message).
    The plus sign (+) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's gen/R.java file that refers to the EditText element. With the resource ID declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.
  • android:layout_width and android:layout_height
    Instead of using specific sizes for the width and height, the "wrap_content" value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "match_parent", then the EditText element would fill the screen, because it would match the size of the parent LinearLayout. For more information, see the Layouts guide.
  • android:hint
    This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string.
    Note: This string resource has the same name as the element ID: edit_message. However, references to resources are always scoped by the resource type (such as id or string), so using the same name does not cause collisions.

Add String Resources

By default, your Android project includes a string resource file at res/values/strings.xml. Here, you'll add two new strings.

  1. From the res/values/ directory, open strings.xml.

  2. Add two strings so that your file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
</resources>

For text in the user interface, always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes the text easier to find and update. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.

Add a Button

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <EditText android:id="@+id/edit_message"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:hint="@string/edit_message" />
        <Button
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/button_send" />
</LinearLayout>

This works fine for the button, but not as well for the text field, because the user might type something longer. It would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout with the weight property, which you can specify using the android:layout_weight attribute.

The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.

The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.

Make the Input Box Fill in the Screen Width

<EditText android:id="@+id/edit_message"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />

Start Another Activity

Respond to the Send Button

  1. In the file res/layout/activity_main.xml, add the android:onClick attribute to the <Button> element as shown below:
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_send"
      android:onClick="sendMessage" />

This attribute tells the system to call the sendMessage() method in your activity whenever a user clicks on the button.

  1. In the file java/com.example.myfirstapp/MainActivity.java, add the sendMessage() method stub as shown below:
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        // Do something in response to button
    }
}

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:

  • Be public
  • Have a void return value
  • Have a View as the only parameter (this will be the View that was clicked)

Build an Intent

An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.

In MainActivity.java, add the code shown below to sendMessage():

public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

There’s a lot going on in sendMessage(), so let’s explain what's going on.
The Intent constructor takes two parameters:

  • A Context as its first parameter (this is used because the Activity class is a subclass of Context)
  • The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started).

The putExtra() method adds the EditText's value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrive the text value. It's a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.

The startActivity() method starts an instance of the DisplayMessageActivity specified by the Intent. Now you need to create the class.

Create the Second Activity

  1. In the Project window, right-click the app folder and select New > Activity > Empty Activity.

  2. In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish

Android Studio automatically does three things:

  • Creates the class DisplayMessageActivity.java with an implementation of the required onCreate() method.

  • Creates the corresponding layout file activity_display_message.xml

  • Adds the required <activity> element in AndroidManifest.xml.

Display the Message

  1. In DisplayMessageActivity.java, add the following code to the onCreate() method:
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_display_message);

   Intent intent = getIntent();
   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
   TextView textView = new TextView(this);
   textView.setTextSize(40);
   textView.setText(message);

   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
   layout.addView(textView);
}
  1. Press Alt + Enter (option + return on Mac) to import missing classes.

There’s a lot going on here, so let’s explain:

  • The call getIntent() grabs the intent that started the activity. Every Activity is invoked by an Intent, regardless of how the user navigated there. The call getStringExtra() retrieves the data from the first activity.

  • You programmatically create a TextView and set its size and message.

  • You add the TextView to the layout identified by R.id.activity_display_message. You cast the layout to ViewGroup because it is the superclass of all layouts and contains the addView() method.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末障簿,一起剝皮案震驚了整個濱河市荚板,隨后出現(xiàn)的幾起案子求妹,更是在濱河造成了極大的恐慌,老刑警劉巖等浊,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件坚冀,死亡現(xiàn)場離奇詭異谆刨,居然都是意外死亡,警方通過查閱死者的電腦和手機纹坐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門枝冀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人恰画,你說我怎么就攤上這事宾茂。” “怎么了拴还?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵跨晴,是天一觀的道長。 經(jīng)常有香客問我片林,道長端盆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任费封,我火速辦了婚禮焕妙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘弓摘。我一直安慰自己焚鹊,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布韧献。 她就那樣靜靜地躺著末患,像睡著了一般。 火紅的嫁衣襯著肌膚如雪锤窑。 梳的紋絲不亂的頭發(fā)上璧针,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天,我揣著相機與錄音渊啰,去河邊找鬼探橱。 笑死,一個胖子當(dāng)著我的面吹牛绘证,可吹牛的內(nèi)容都是我干的隧膏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼嚷那,長吁一口氣:“原來是場噩夢啊……” “哼胞枕!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起车酣,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤曲稼,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后湖员,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贫悄,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年娘摔,在試婚紗的時候發(fā)現(xiàn)自己被綠了窄坦。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡凳寺,死狀恐怖鸭津,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情肠缨,我是刑警寧澤逆趋,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站晒奕,受9級特大地震影響闻书,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜脑慧,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一魄眉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧闷袒,春花似錦坑律、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至淘捡,卻和暖如春藕各,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背焦除。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工激况, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人膘魄。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓乌逐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親创葡。 傳聞我的和親對象是個殘疾皇子浙踢,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容