Android Activity: Basic usage of Android activities, Toast Message & Menu
Table of Contents
What is the android activity?
Android activity is the easiest place to attract users. It is a component that can contain a user interface. Mainly used to interact with users. An application can contain zero or more activities but does not contain any activities Applications are rare. Who doesn’t want their applications to never be seen by users?.
Basic usage of Android activity
So far, you have not manually created an android activity yet, because the HelloWorldActivity in the previous article is ADT Help us create it automatically. Creating activities manually can deepen our understanding, so now is the time to do it yourself. First, you need to create a new Android project, the project name can be called ActivityTest, we use the package name The default value is com.example.activitytest. You have learned the steps of creating a new project in the previous article, Needs to be slightly modified, we no longer check the Create Activity option, because this time we are going to create manually Build activities, as shown in Figure1.
Click Finish and the project is created. At this time, there should be two projects in your Eclipse, ActivityTest, And HelloWorld. It is highly recommended that you close irrelevant projects and only open the projects needed for the current work, otherwise, I Guarantee that you will suffer in this respect in the future. It is best to right-click the HelloWorld project→Close Project now.
Manually create android Activity event:
At present, the src directory of the ActivityTest project should be empty, and you should add a package under the src directory. Click on File→New→Package in the Eclipse navigation bar, fill in the default package name used when we create a new project in the pop-up window com.example.activitytest, click Finish. The directory structure after adding the package is shown in Figure2.
Now right-click the com.example.activitytest package→New→Class, a dialog box for creating a new class will pop up, we create A class named FirstActivity, and let it inherit from Android activity, click Finish to complete the creation. You need to know that any android activity in the project should override the onCreate() method of Android activity, but currently our There is no code inside FirstActivity, so the first thing you have to do is to rewrite onCreate() in FirstActivity Method, the code is as follows:
1 2 3 4 5 6 |
public class FirstActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } } |
As you can see, the onCreate() method is very simple, that is, the onCreate() method of the parent class is called. Of course, this is just silent To realize the recognition, we need to add a lot of our own logic later.
Create and load the android activity layout:
As we said earlier, the design of Android programs pays attention to the separation of logic and views. It is best that each android activity corresponds to one A layout, the layout is used to display the content of the interface, so we will now manually create a layout file. Right-click the res/layout directory→New→Android XML File, and a window for creating a layout file will pop up. We give this The layout file is named first_layout, and the root element is selected as LinearLayout by default, as shown in Figure3.
Click Finish to complete the creation of the layout. At this time you will see the window shown in Figure4.
This is the visual layout editor provided by ADT. You can preview the current layout in the central area of the screen. There are two switching cards at the bottom of the window, Graphical Layout on the left and first_layout.xml on the right. Graphical Layout is the current visual layout editor, where you can not only preview the current layout but also drag and drop Way to edit the layout. And first_layout.xml is to edit the layout through an XML file, now click First_layout.xml switch card, you can see the following code:
1 2 3 4 5 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> |
Since we just selected LinearLayout as the root element when creating the layout file, now in the layout file There is already a LinearLayout element. Then we will edit this layout a bit and add a button, as follows Shown:
1 2 3 4 5 6 7 8 9 10 11 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 1" /> </LinearLayout> |
A Button element is added here, and several attributes are added inside the Button element. android:id is for The current element defines a unique identifier, which can then be manipulated in the code. You might be @+id/button_1 This syntax is unfamiliar, but if you remove the plus sign and become @id/button_1, you will feel Be familiar with it. Isn’t this the syntax for referencing resources in XML? It’s just replacing string with id. Yes, If you need to refer to an id in XML, use the syntax @id/id_name, and if you need to in XML To define an id, use the syntax @+id/id_name. Then android:layout_width specifies the current element Use match_parent to indicate that the current element is as wide as the parent element. android:layout_height specified The height of the current element, wrap_content is used here, which means that the height of the current element can just contain the inner Rong will do. android:text specifies the text content displayed in the element. If you still can’t fully understand, it’s okay, I will focus on the detailed content of the layout in the next article, this article just briefly touches on it first. Now the button is After adding, you can click back to the Graphical Layout switch card to preview the current layout, as shown in Figure5.
As you can see in the central preview area, the button has been successfully displayed, so that a simple layout is written It’s done. So what we have to do next is to load this layout in the android activity. Go back to FirstActivity and add the following code to the onCreate() method:
1 2 3 4 5 6 7 |
public class FirstActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.first_layout); } } |
As you can see, the setContentView() method is called here to load a layout for the current android-activity, and in In the setContentView() method, we usually pass in the id of a layout file. When introducing the gen directory in my previous Article, As I mentioned, any resource added to the project will generate a corresponding resource id in the R file, so we just The id of the first_layout.xml layout just created should now be added to the R file. Quoting cloth in the code You have also learned the method of the bureau file, just call R.layout.first_layout to get first_layout.xml The id of the layout, and then pass this value to the setContentView() method. Note that the R we used here is The R file under the com.example.activitytest package, the Android SDK will also automatically provide an R file under the android package Piece, don’t use it wrong.
Register android activity in AndroidManifest file:
Don’t forget that I said earlier that all activities must be registered in AndroidManifest.xml to take effect. So let’s open AndroidManifest.xml to register FirstActivity, the code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.activitytest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".FirstActivity" android:label="This is FirstActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
As you can see, the registration statement of the android activity should be placed in the <application> tag, here is through the <activity> tag to Activities are registered. First of all, we have to use android:name to specify which event to register, then fill in here What does .FirstActivity mean? In fact, this is just short for com.example.activitytest.FirstActivity That’s it. Because the package name of the program has been specified through the package attribute in the outermost <manifest> tag com.example.activitytest, so this part can be omitted when registering an activity and use. FirstActivity directly Will suffice. Then we use android:label to specify the content of the title bar in the android activity, the title bar is displayed in the most android activity At the top, you will see it later when it runs. It’s important to note that the label assigned to the main android activity will not only become
The content in the title bar will also become the name displayed by the application in the Launcher. Then mark in <activity> We added the <intent-filter> tag inside the sign, and added <action android:name= to this tag “android.intent.action.MAIN” /> and <category android:name=”android.intent.category.LAUNCHER” />
These two statements. I have already explained this before, if you want FirstActivity as our program The main activity, that is, this android activity is the first to open when you click the desktop application icon, so you must add these two statements. Also note that if your application does not declare any android activity as the main activity, this application is still available It is installed normally, but you cannot see or open this program in the launcher. This kind of procedure is generally regarded as the third party services are used internally by other applications, such as Alipay Express Payment Service. Ok, now everything is ready, let’s run the program, the result is shown in Figure6.
At the very top of the interface is a title bar, which displays the content we just specified when registering for the event. Title Below is the interface written in the layout file first_layout.xml, you can see the button we just defined. Present After you have successfully mastered the method of manually creating activities, let us continue to see what you can do more in activities thing.
Hide title bar in android activity:
There are actually quite a few operations that can be performed in the title bar, especially since the Action Bar was added after the Android 4.0 Function. However, some people think that the title bar takes up a lot of screen space, making the content area smaller, so there are many The application will choose to hide the title bar. The hiding method is very simple. Open FirstActivity and add the following code in the onCreate() method:
1 2 3 4 5 6 |
protected void onCreate(Bundle savedInstanceState) { 36 super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.first_layout); } |
Where requestWindowFeature(Window.FEATURE_NO_TITLE) means not to display in the android activity Title bar, note that this code must be executed before setContentView(), otherwise an error will be reported. Run the program again, The effect is shown in Figure7.
In this way, the title bar will no longer be displayed in our event, it looks like a lot of space!
Use Toast in android activity:
Toast is a very good reminder method provided by the Android system. You can use it in the program Information is notified to the user. This information will disappear automatically after a period of time and will not occupy any screen space. We now Just try to use Toast in activities. First, you need to define a trigger point to pop up Toast. There is a button on the interface, then we will let you click this button When the button is pressed, a Toast pops up. Add code in the onCreate() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.first_layout); 37 Button button1 = (Button) findViewById(R.id.button_1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show(); } }); } |
In the android activity, you can get the elements defined in the layout file through the findViewById() method. Here we pass Enter R.id.button_1 to get an instance of the button. This value is just passed the android:id attribute in first_layout.xml Specified. What the findViewById() method returns is a View object, we need to downcast it to Button Object. After getting the button instance, we register a listener for the button by calling the setOnClickListener() method When the button is clicked, the onClick() method in the listener will be executed. Therefore, the function of popping up Toast is of course Written in the onClick() method. The usage of Toast is very simple. Create a Toast object through the static method makeText(), and then call show() Just display the Toast. It should be noted here that the makeText() method needs to pass in three parameters. the first parameter is Context, which is the context required by Toast. Since the android activity itself is a Context object, Here you can directly pass in FirstActivity.this. The second parameter is the text content displayed by Toast, and the third parameter is Toast For the displayed duration, there are two built-in constants to choose from Toast.LENGTH_SHORT and Toast.LENGTH_LONG. Now run the program again and click the button, the effect is shown in Figure8.
Use Menu in android activity:
Don’t know if you remember, when you created your first Android project in the previous article, ADT An onCreateOptionsMenu() method is automatically created in HelloWorldActivity. This method is used in activities Since our focus was not here at the time, we directly ignored the menu creation in the menu. Now we can analyze it carefully. Down. After all, a mobile phone is different from a computer, and its screen space is very limited, so make full use of the screen space to set up the phone interface. The calculation becomes very important. If there are a lot of menus to be displayed in your activity, the interface design will be better than It is more embarrassing, because these menus alone may take up nearly one-third of the screen space. What should I do? do not worry, Android provides us with a way to display the menu without taking up any screen space.
First, create a menu folder under the res directory, right-click the res directory→New→Folder, and enter the folder name menu, click Finish. Then create a new menu file named main in this folder, right-click the menu file
Folder→New→Android XML File, as shown in Figure9.
Enter main for the file name and click Finish to complete the creation. Then add the following code in main.xml:
1 2 3 4 5 6 7 8 |
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/add_item" android:title="Add"/> <item android:id="@+id/remove_item" android:title="Remove"/> </menu> |
Here we have created two menu items, of which the <item> tag is used to create a specific menu item, and then Use android:id to assign a unique identifier to this menu item, and assign a name to this menu item through android:title. Then open FirstActivity and rewrite the onCreateOptionsMenu() method. The code is as follows:
1 2 3 4 |
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } |
You can get the MenuInflater object through the getMenuInflater() method, and then call its inflate() method to give The current android activity creates a menu. The inflate() method receives two parameters, the first parameter is used to specify which resource we pass File to create the menu, here of course we pass in R.menu.main, the second parameter is used to specify where our menu item will be added In a Menu object, the menu parameter passed in the onCreateOptionsMenu() method is directly used here. Then give This method returns true, indicating that the created menu is allowed to be displayed. If false is returned, the created menu will not be displayed. Of course, it is not enough to just show the menu. We define the menu not only for viewing but the key is to make the menu true It is only available, so we need to define the menu response event. Override onOptionsItemSelected() in FirstActivity method:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add_item: Toast.makeText(this, "You clicked Add", Toast.LENGTH_SHORT).show(); break; case R.id.remove_item: Toast.makeText(this, "You clicked Remove", Toast.LENGTH_SHORT).show(); break; default: } 40 return true; } |
In the onOptionsItemSelected() method, by calling item.getItemId() to determine which menu we clicked Item, and then add your own logic processing to each menu item, here we live to learn and use, pop up a Toast just learned. Re-run the program and press the Menu button, the effect is shown in Figure10.
As you can see, the menu is not displayed by default, and the menu will be displayed at the bottom only if the Menu button is pressed Come, so we can use the menu with confidence because it won’t take up any space for activities. Then click Add menu item, the effect is shown in Figure11.