AndroidTraining学习------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:

Add a Text Field

In the activity_main.xml file, within the element, add the following 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 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 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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值