Estava eu estudando um pouco de android (comecei a brincar disso esses dias) e queria colocar objetos diferentes na tela do meu aplicativo dependendo da ação realizada pelo usuário.
A ideia era que se o usuário pressionasse o botão 1 alguns objetos aparecessem na tela, mas se o botão 2 fosse pressionado, outros objetos aparecessem.
Fiquei lendo alguns tutoriais pra descobrir uma forma de fazer isso, mas não encontrei a resposta em um único lugar, por esta razão, depois de ler vários tutoriais e descobrir como fazer resolvi escrever este post.
A minha ideia foi criar dois frames, no primeiro frame haveriam 2 botões (botão 1 e botão 2 - bem criativo). Se o botão 1 fosse pressionado, apareceriam os botões 3 e 4 no frame 2. Caso fosse pressionado o botão 2, os botões 5, 6 e 7 apareceriam no frame 2.
Vejam, assim como foi feito com botões, poderiam ter sido utilizados outros objetos. É que fazer com botões era mais fácil e num precisava de muita criatividade, por isso optei por essa opção. (Na verdade, eu nem acho que tinha uma opção, mas isso não é assunto pra esse blog).
Pois bem, pra montar meu super projetinho foi utilizado o eclipse INDIGO (Xupa JUNO).
Inicialmente eu criei um projetinho android no eclipse com os seguintes passos:
File -> New -> Android Application Project
Tela New Android Application:
Application Name = BotoesInterativos
Project Name = BotoesInterativos
Package Name = com.example.botoesinterativos
Build SDK = Android 4.1 (API16)
Minimum Required SDK = API8: Android 2.2 (Froyo)
Clicar NEXT
Tela Create Activity:
Selecionar o checkbox 'Create Activity'
Selecionar a opção BlankActivity
Clicar NEXT
Tela New Blank Activity
Activity Name = MainActivity
Layout_name = activity_main
Navigation Type = None
Title = MainActivity
Pronto, uma vez criado o projeto, iremos alterar o arquivo activity_main.xml que se encontra no diretório res/layout. Este arquivo tem o seguinte formato.
<RelativeLayout 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"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/frameLayout1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:background="#ABABAB">
<Button
android:id="@+id/botao1"
android:layout_width="90dp"
android:layout_height="35dp"
android:text="Botão 1"
android:textSize="10sp"/>
<Button
android:id="@+id/botao2"
android:layout_width="90dp"
android:layout_height="35dp"
android:text="Botão 2"
android:layout_toRightOf="@+id/botao1"
android:textSize="10sp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/frameLayout1"
android:id="@+id/frameLayout2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:background="#ABABAB">
<TableLayout
android:id="@+id/tableLayoutFrame2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="horizontal"
android:shrinkColumns="0">
</TableLayout>
</RelativeLayout>
</RelativeLayout>
Observe que foram utilizados 2
RelativeLayout. No primeiro, existem os botões 1 e 2, enquanto que no segundo
existe um TableLayout que será utilizado para colocarmos os demais botões
dinamicamente.
Em seguida, alteramos o arquivo MainActitivity.java
para ficar da seguinte forma:
package com.example.botoesinterativos;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TableRow tr = new TableRow(this);
//Botões para
opção botão 1
final Button botao3 = new Button(this);
final Button botao4 = new Button(this);
botao3.setText("Botão 3");
botao4.setText("Botão 4");
botao3.setTextSize(10);
botao4.setTextSize(10);
botao3.setWidth(135);
botao4.setWidth(135);
botao3.setMinimumHeight(30);
botao4.setMinimumHeight(30);
botao3.setHeight(35);
botao4.setHeight(35);
//Botões para
opção botão 2
final Button botao5 = new Button(this);
final Button botao6 = new Button(this);
final Button botao7 = new Button(this);
botao5.setText("Botão 5");
botao6.setText("Botão 6");
botao7.setText("Botão 7");
botao5.setTextSize(10);
botao6.setTextSize(10);
botao7.setTextSize(10);
botao5.setWidth(135);
botao6.setWidth(135);
botao7.setWidth(135);
botao5.setMinimumHeight(30);
botao6.setMinimumHeight(30);
botao7.setMinimumHeight(30);
botao5.setHeight(35);
botao6.setHeight(35);
botao7.setHeight(35);
final Button botao1 = (Button) findViewById(R.id.botao1);
botao1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Obtém o TableLayout
TableLayout ll =
(TableLayout) findViewById(R.id.tableLayoutFrame2);
//Limpa
as views criadas anteriormente
tr.removeAllViews();
ll.removeAllViews();
//Adiciona
os botões à tabela
tr.addView(botao3);
tr.addView(botao4);
int lHeight = RelativeLayout.LayoutParams.FILL_PARENT;
int lWidth = RelativeLayout.LayoutParams.WRAP_CONTENT;
//Adiciona a tabela ao TableLayout
ll.addView(tr, new RelativeLayout.LayoutParams(lHeight,
lWidth));
}
});
final Button botao2 = (Button) findViewById(R.id.botao2);
botao2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Obtém o TableLayout
TableLayout ll =
(TableLayout) findViewById(R.id.tableLayoutFrame2);
//Limpa
as views criadas anteriormente
tr.removeAllViews();
ll.removeAllViews();
//Adiciona
os botões à tabela
tr.addView(botao5);
tr.addView(botao6);
tr.addView(botao7);
int lHeight = RelativeLayout.LayoutParams.FILL_PARENT;
int lWidth = RelativeLayout.LayoutParams.WRAP_CONTENT;
//Adiciona a tabela ao TableLayout
ll.addView(tr, new RelativeLayout.LayoutParams(lHeight,
lWidth));
}
});
}
}
Note que nesta classe é criado um objeto tr (TableRow). Cada objeto inserido neste TableRow será uma coluna da tabela. Em seguida, são criados os botões 3, 4, 5, 6 e 7. O próximo passo é criar os eventos que serão utilizados pelos botões 1 e 2 para que os botões 3, 4, 5, 6 e 7 possam aparecer na tela.
As figuras abaixo mostram como ficou a tela da aplicação. Na primeira figura, nenhum botão foi pressionado. Na segunda, o botão 1 foi pressionado e apareceram os botões 3 e 4. Na última figura, o botão 2 foi pressionado e apareceram os botões 5, 6 e 7.



Obrigado pelo post... Funcionou lindamente ....
ResponderExcluir=D