Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лабораторная работа Android.docx
Скачиваний:
1
Добавлен:
01.03.2025
Размер:
1 Мб
Скачать
☆
    1. Создание activity и переходы между экранами

Мы подобрались к очень интересной теме. До этого мы создавали приложения, которые содержали только один экран (Activity). Но если вы пользуетесь смартфоном с Android, то вы замечали, что экранов в приложении обычно больше. Если рассмотреть, например, почтовое приложение, то в нем есть следующие экраны: список аккаунтов, список писем, просмотр письма, создание письма, настройки и т.д.

Итак, если мы хотим создать еще одно Activity, надо создать класс и прописать Activity в AndroidManifest.xml. Создадим для примера активити с для отображения данных о поездке. Чтобы создать класс, жмем правой кнопкой на package com.tsu.tripcomputer в папке проекта и выбираем New -> Class. В появившемся окне вписываем имя класса TripActivity и имя наследника Activity, а затем нажимаем Finish.

Для корректной работы необходимо добавить новое activity также в Manifest файл:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.tsu.tripcomputer"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk

android:minSdkVersion="7"

android:targetSdkVersion="15" />

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/title_activity_main" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity

android:name=".TripActivity"

android:label="Current trip" >

</activity>

</application>

</manifest>

Теперь добавим код для вызова этого нового активити в MainActivity.java.

Button btn = (Button)this.findViewById(R.id.btnStart);

btn.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, TripActivity.class);

MainActivity.this.startActivity(intent);

}});

На этом этапе, запустите приложение и проверьте, чтобы все работало, при переходе на новое активити будет виден пустой экран.

Итак у нас появился класс описывающий новый экран, теперь добавим layout файл для него. Нажимаем Ctr-N, выбираем Android XML Layout File и жмем Next.

На следующем экране вписываем activity_trip и жмем Finish.

Заполним новый layout следующим контентом:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:layout_margin="20dip"

android:orientation="vertical" >

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content" >

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Текущая поездка" />

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="2dip"

android:layout_marginBottom="5dip"

android:background="@android:color/darker_gray" >

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content" >

<TextView

android:id="@+id/textView2"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_gravity="right|fill_vertical"

android:layout_weight="1"

android:text="Дистанция" />

<TextView

android:id="@+id/textViewDistance"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_gravity="right"

android:layout_weight="1"

android:text="0" />

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content" >

<TextView

android:id="@+id/TextView01"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Время" />

<TextView

android:id="@+id/textViewTime"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="0" />

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content" >

<TextView

android:id="@+id/TextView01"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Средняя скорость" />

<TextView

android:id="@+id/textViewSpeed"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="0" />

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content" >

<TextView

android:id="@+id/TextView01"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Топливо" />

<TextView

android:id="@+id/TextViewFuel"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="0" />

</LinearLayout>

<RelativeLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginTop="10dip" >

<Button

android:id="@+id/btnUpdateTrip"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentRight="true"

android:minWidth="100dip"

android:text="Обновить" />

</RelativeLayout>

</LinearLayout>

</LinearLayout>

Теперь необходимо добавить код для загрузки данного layout из xml в файл TripActivity.java:

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_trip);

}

Вот что должно получиться после перехода на вторую Activity: