Você está na página 1de 57

Android Prtico App 1

Instrutor
Jogo Guess The Number
Jogo em que o usurio tenta adivinhar um nmero sorteado no menor nmero
de tentativas
Jogo Guess The Number
Telas que vamos produzir
Criando o Projeto
Baixe o pacote em: developer.android.com/sdk/index.html

Crie uma nova


aplicao
Android
Preenchendo os Dados

Ateno aos
3 nveis de
API!
Preenchendo os Dados
Preenchendo os Dados

Partiremos de
uma Activity sem
contedo
Preenchendo os Dados
Diretrios Iniciais
Activity
Criada

SDK
Android

Diretrios
Recursos

Descritor
Aplicao
Diretrios Iniciais
assets
Recursos (Raw Bytes)
no indexados no R.java
lidos com
AssetManager

res
Recursos indexados no
R.java

drawable
cones descritor
Permisses,
layout Activities, etc
telas

values
Strings e I18N
R.java ndice de Recursos
package com.android.games; Arquivo criado
automaticamente com a
public final class R { edio dos recursos
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}
Activity automaticamente criada
package com.android.games; Cdigo criado
automaticamente
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class GuessTheNumber extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guess_the_number);
}
...
}
strings.xml modo texto

Nome e Valor
da String
Criando strings novas
<?xml version="1.0" encoding="utf-8"?>
<resources>
Vamos criar novos
<string name="try_bt">Try!</string>
valores
<string name="hello">Guess The Number</string>
<string name="app_name">GuessTheNumber</string>
<string name="top">Top 10</string>
<string name="new_game">Start New Game</string>
<string name="msg_value_greater">%d is greater than the expected number!</string>
<string name="msg_value_less">%d is lesser than the expected number!</string>
<string name="msg_value_correct">You win: %d.</string>
<string name="msg_new_game">New Game Started!</string>
<string name="lname">Enter name:</string>
<string name="lvalue">Enter your guess: (0-1000)</string>
<string name="dialog_start_title">Guess the number</string>
<string name="alert_dialog_ok">Ok</string>
<string name="alert_dialog_cancel">Cancel</string>
<string name="dialog_name_msg">Enter player\'s name:</string>
<string name="msg_try_error">Please start game and enter a player\'s name.</string>
</resources>
Criando atributos na Activity
public class GuessTheNumber extends Activity {

// Application log tag


public static final String LOG_TAG = "GUESSTHENUMBER";

// Expected number
private int iNumber = -1;

// Number of tries
private int iTries = 0;

// Player's name
private String mPlayerName;

// Start dialog ID
static final int DIALOG_START_ID = 0;

Todos os direitos reservados ao Instituto de Pesquisas Eldorado - 2012


Gerando o nmero
import android.widget.Toast;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
generateRandomNumber();
}
private void generateRandomNumber(){
iNumber = (int)(Math.random()*1000);
iTries = 0;
}

private void showToast(String text) {


Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}

Todos os direitos reservados ao Instituto de Pesquisas Eldorado - 2012


Depurar a aplicao

Todos os direitos reservados ao Instituto de Pesquisas Eldorado - 2012


Configurando
Clique duplo
para criar nova
configurao Nome da
configurao

Buscar o
projeto
Configurar Target

Criar Virtual
Devices
Criando AVD

Novo
Android Virtual
Device (AVD)
Criando AVD
Nome
AndroidDevice

Target API

Propriedades
Hardware
Clicar em OK
Apply e debug
Selecione o novo
Device

Clique Debug
Subindo emulador

Emulador exige bastante


recursos da mquina
Abrindo DDMS

Perspectiva DDMS
Dalvik Debug Monitor Server
Processos
DDMS
DDMS

Outras
Informaes
Screen
Capture

Logcat
Screen Capture

Tela do Device

comum em mquinas mais


lentas executando o
emulador aparecerem telas
de App not Responding.

Na maioria clique em Wait


Tela Inicial
Botes do
Device

Tela main da
nossa aplicao

Teclado do Device
ausente nas
CTRL+F11 altera ltimas verses
Portrait/Landscap do emulador,
e input feito pelo
teclado do
computador
layout graficamente
Config da Tela
Portrait
Landscape

OutLine Hierarquia
UI do Device de Objetos

Layouts de UI

Propriedades do
Objetos de UI
Objeto selecionado
Alterando TextView
Alterar as
Propriedades

Clicar no Text
View

<TextView
android:layout_height="wrap_content"
android:text="@string/hello"
android:layout_width="wrap_content"
android:layout_gravity="center" />
Editando layout visualmente
Layouts

Observe que os
FrameLayout vo
aparecer no Outline

As linhas guias
ajudam a visualizar
o posicionamento
do novo objeto
Arrastar e soltar 2
FrameLayout
Editando layout visualmente

Clique em cada
FrameLayout

Preencha essas
propriedades

<FrameLayout
android:id="@+id/FrameLayout01" <FrameLayout
android:id="@+id/FrameLayout02"
android:layout_gravity="center"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_width="fill_parent"
android:layout_weight="1"> android:layout_weight="3">
Editando layout visualmente

Perceba que os
LinearLayout so criados
Arrastar e soltar 2 dentro dele no Outline
LinearLayout dentro do
FrameLayout01
Editando layout visualmente
Clicando com o boto direito do mouse no
LinearLayout02 temos opes de
Adicionar/Remover ou mover Up/Down

Clique em Down para colocar o


LinearLayout02 dentro do
FrameLayout02
Editando layout visualmente

Veja a hierarquia
na estrutura

<LinearLayout android:id="@+id/LinearLayout01"
android:layout_gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:layout_height="wrap_content"
E ajuste as
android:layout_width="fill_parent">
propriedades

<LinearLayout android:id="@+id/LinearLayout02"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_gravity="center_horizontal">
Obtenha essa
estrutura

Perceba que agora estamos alterando


tambm os IDs dos Objetos e colocando
nomes de mtodos que ainda no
criamos (onClick)

<EditText
<Button android:id="@+id/Button_new_game"
android:layout_gravity="center_vertical
android:layout_height="wrap_content" |center_horizontal"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:text="@string/new_game" android:layout_height="wrap_content"

android:onClick="onClick" /> android:inputType="number"


android:id="@+id/EditTextGuess"/>

<Button android:id="@+id/Button_try"
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="@string/lvalue" android:layout_gravity="center_vertical
|center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
android:text="@string/try_bt"
android:onClick="onClick" />
Incluir no LinearLayout02 um TextView
(de Views) e um ListView( de Layouts)

<TextView android:text="@string/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:id="@+id/TextViewTop10/>
<ListView android:id="@+id/ListViewTop10"
android:layout_height="fill_parent"
android:layout_width="fill_parent/>
Criando start_dialog.xml em layout

Clicar com o boto direito sobre


diretrio layout e selecionar
New -> File
start_dialog.xml modo texto

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp >
<TextView android:id="@+id/start_dialog_textview"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="@string/dialog_name_msg"
android:textColor="#FFF />
<EditText android:id="@+id/start_dialog_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content />
</LinearLayout>
Criando list_row.xml em layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:id="@+id/TextViewPlayerName"
android:text="Player name"/>

<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:gravity="center_horizontal"
android:id="@+id/TextViewTries"
android:text="Score"/>
</LinearLayout>
Mtodo onTryNumber na activity
import android.util.Log;
import android.widget.EditText;
...
public void onTryNumber(String newNumber){
String msg;
int newIntNumber = 0;
// in case there is no player name, force user to insert one
if (mPlayerName == null || mPlayerName.equals("")) {
showToast(getString(R.string.msg_try_error));
return;
}
try {
newIntNumber = Integer.parseInt(newNumber);
} catch (NumberFormatException nf) {
newIntNumber = 0;
}
msg = checkNumber(newIntNumber);
Log.d(LOG_TAG, msg);
// Updates the UI with a toast message and clears the inputed guess
showToast(msg);
EditText textComp = (EditText) findViewById(R.id.EditTextGuess);
textComp.setText("");
}
Mtodo checkNumber
private String checkNumber(int newIntNumber) {
String msg;
if (newIntNumber > iNumber) {
// The guessed number is greater than the expected number
msg = getResources().getString(R.string.msg_value_greater, newIntNumber);
iTries++;
} else if (newIntNumber < iNumber) {
// The guessed number is lesser than the expected number
msg = getResources().getString(R.string.msg_value_less, newIntNumber);
iTries++;
} else {
// The guessed number is the expected number
msg = getResources().getString(R.string.msg_value_correct, newIntNumber)
+ "\n" + getResources().getString(R.string.msg_new_game);
generateRandomNumber();
}
return msg;
}
Mtodo onClick
import android.view.View;
...

public void onClick(View view) {


switch (view.getId()) {

case R.id.Button_try:
EditText tryEntry = (EditText)findViewById(R.id.EditTextGuess);
onTryNumber(tryEntry.getText().toString());
break;

case R.id.Button_new_game:
showDialog(DIALOG_START_ID);
break;
}
}
import android.app.Dialog; Mtodo onCreateDialog
import android.view.LayoutInflater;
import android.app.AlertDialog;
import android.content.DialogInterface;
protected Dialog onCreateDialog(int id) {
mPlayerName = null;
switch(id) {
case DIALOG_START_ID:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.start_dialog, null);
return new AlertDialog.Builder(GuessTheNumber.this)
.setTitle(R.string.dialog_start_title)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textComp = (EditText)textEntryView.findViewById(R.id.start_dialog_edittext);
mPlayerName = textComp.getText().toString();
onNewGame();
}
}).setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textComp = (EditText)textEntryView.findViewById(R.id.start_dialog_edittext);
textComp.setText("");
}
}).create();
}
return null;
}
Mtodo onNewGame
public void onNewGame(){
showToast(getResources().getString(R.string.msg_new_game));
generateRandomNumber();
}

Vamos Jogar?
Jogando o game
Criar um novo
Jogo

Voltar pode
desaparecer o
teclado
numrico ou
sair do game

Campo para
Teclado chutar valor
Numrico
Criando classe TopTenList

package com.android.games;

public class TopTenList {


Crie uma nova classe
chamada TopTenList
}
Criando classe TopTenList
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
...
public class TopTenList {
private static final String DATABASE_CREATE =
"create table toplist (_id integer primary key autoincrement, "
+ "player text not null, score text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "toplist";
private static final int DATABASE_VERSION = 1;

private final Context mCtx;

public static final String KEY_PLAYER = "player";


public static final String KEY_SCORE = "score";
public static final String KEY_ROWID = "_id";

private SQLiteDatabase mDb;


private DatabaseHelper mDbHelper;

public TopTenList(Context ctx) {


this.mCtx = ctx;
}
Inner Class DatabaseHelper
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
...
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(GuessTheNumber.LOG_TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS toplist");
onCreate(db);
}
}

Todos os direitos reservados ao Instituto de Pesquisas Eldorado - 2012


Inner Class DatabaseHelper
import android.database.SQLException;
import android.content.ContentValues;
import android.database.Cursor;
...
public TopTenList open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDb = null;
mDbHelper.close();
}
public long createPlayer(String player, String score) {
ContentValues values = new ContentValues();
values.put(KEY_PLAYER, player);
values.put(KEY_SCORE, score);
return mDb.insert(DATABASE_TABLE, null, values);
}
public Cursor fetchAllNotes() {
String[] columns = {KEY_ROWID, KEY_PLAYER, KEY_SCORE};
return mDb.query(DATABASE_TABLE, columns, null, null, null, null, KEY_SCORE + " asc");
}
Alterando atributo e onCreate na activity
// Helper to add to top 10 list
private TopTenList mDbHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
generateRandomNumber();

mDbHelper = new TopTenList(this);


mDbHelper.open();
fillData();
}
fillData que popula a list_row
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
import android.widget.ListView;
...
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);

// Create an array to specify the fields we want to display in the list


String[] from = new String[]{TopTenList.KEY_PLAYER, TopTenList.KEY_SCORE};

// and an array of the fields into the layout we want to bind those fields to
// (in this case just text1)
int[] to = new int[]{R.id.TextViewPlayerName, R.id.TextViewTries};

// Now create a simple cursor adapter and set it to display


SimpleCursorAdapter topList =
new SimpleCursorAdapter(this, R.layout.list_row, notesCursor, from, to);

ListView listComp = (ListView)findViewById(R.id.ListViewTop10);


listComp.setAdapter(topList);
}
Todos os direitos reservados ao Instituto de Pesquisas Eldorado - 2012
Alterando o checkNumber
private String checkNumber(int newIntNumber) {
String msg;
if (newIntNumber > iNumber) {
// The guessed number is greater than the expected number
msg = getResources().getString(R.string.msg_value_greater, newIntNumber);
iTries++;
} else if (newIntNumber < iNumber) {
// The guessed number is lesser than the expected number
msg = getResources().getString(R.string.msg_value_less, newIntNumber);
iTries++;
} else {
// The guessed number is the expected number
msg = getResources().getString(R.string.msg_value_correct, newIntNumber)
+ "\n" + getResources().getString(R.string.msg_new_game);

addScore();
generateRandomNumber();
}
return msg;
}
Criando o addScore
public void addScore(){
mDbHelper.createPlayer(mPlayerName, Integer.toString(iTries));
fillData();
}

Desafio voc bater o meu recorde de 7


tentativas nesse jogo !!!
Finalizando com i18n

Clique com boto direito


no res

Criar um novo diretrio

Chamar o diretrio
values-pt
Criar strings.xml no values-pt
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Adivinha o Numero</string>
<string name="app_name">Adivinha o Numero</string>
<string name="try_bt">Tentar Nmero</string>
<string name="new_game">Iniciar Novo Jogo</string>
<string name="msg_value_greater">%d maior que o numero esperado!</string>
<string name="msg_value_less">%d menor que o numero esperado!</string>
<string name="msg_value_correct">Voc venceu: %d.</string>
<string name="msg_new_game">Novo Jogo Iniciado!</string>
</resources>
main.xml com locale
main.xml com Locale pt

Strings no declaradas no values-pt


sero recuperadas do values
Perguntas?

Você também pode gostar