1
Well I have an application that would like to keep the standard format on all screens, i have a quick access menu with some items in the action bar, and other complete in the menu option.
The problem is that as I am using the ListActivity
This is not working.
I do not understand very well this part of extensions, if someone has a good material that explains, in Portuguese please, I thank you.
My menu XML code:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
tools:context="com.example.starlighting.MainActivity" >
<item
android:id="@+id/menugerenceditar"
android:icon="@drawable/editar"
android:orderInCategory="1"
android:title="Editar"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/menuadd"
android:icon="@drawable/site"
android:orderInCategory="2"
android:title="Gerenciar"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/menuremov"
android:icon="@drawable/site"
android:orderInCategory="3"
android:title="Importar"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/menuexportar"
android:icon="@drawable/site"
android:orderInCategory="4"
android:title="exportar"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/menuimportar"
android:icon="@drawable/site"
android:orderInCategory="5"
android:title="Star Lighting"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/menusair"
android:icon="@drawable/sair"
android:orderInCategory="100"
android:title="Sair"
app:showAsAction="ifRoom"/>
</menu>
My code of flater menu:
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if(featureId == Window.FEATURE_ACTION_BAR && menu != null){
if(menu.getClass().getSimpleName().equals("MenuBuilder")){
try{
Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
m.setAccessible(true);
m.invoke(menu, true);
} catch(NoSuchMethodException e){
} catch(Exception e){
throw new RuntimeException(e);
}
}
}
return super.onMenuOpened(featureId, menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.gerenciar, menu);
getMenuInflater().inflate(R.menu.gerenciarescondido, menu);
onMenuOpened(Window.FEATURE_ACTION_BAR, menu);
return true;
}
//seta as opções de função dos itens do menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.menugerenceditar) {
//List<Lista> lista = gerarlista(tabbanco);
//final Listaadapter listasadapter = new Listaadapter(this, lista);
//setListAdapter(listasadapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Lista tabela = listasadapter.getItem(position);
Intent intent = new Intent(gerenciar.this, gerenciartabela.class);
//intent.putExtra("tabela", tabela.getNome());
startActivity(intent);
}});
return true;
}
if (id == R.id.menuadd) {
Intent intent = new Intent(gerenciar.this, adcionartabela.class);
startActivity(intent);
return true;
}
if(id==R.id.menuremov){
return true;
}
if (id == R.id.menusair) {
AlertDialog.Builder mensagem =
new AlertDialog.Builder(gerenciar.this);
mensagem.setTitle("Atenção!");
mensagem.setMessage("Deseja realmente sair?");
mensagem.setIcon(R.drawable.sair);
mensagem.setPositiveButton("Sim",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
gerenciar.this.finish();
}});
mensagem.setNegativeButton("Não",null);
mensagem.show();
return true;
}
if (id == R.id.menuexportar) {
return true;
}
if (id == R.id.menuimportar) {
return true;
}
return super.onOptionsItemSelected(item);
}
My code 'list'
package com.example.app;
public class Lista {
private String nome;
// private int idade;
// private int imagem;
public Lista() {
}
public Lista(String nome) {
super();
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Override
public String toString() {
return nome;
}
}
My code 'list Adapter'
package com.example.app;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class Listaadapter extends ArrayAdapter<Lista> {
private Context context;
private List<Lista> lista = null;
public Listaadapter(Context context, List<Lista> lista) {
super(context,0, lista);
this.lista = lista;
this.context = context;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
Lista tabela = lista.get(position);
if(view == null)
view = LayoutInflater.from(context).inflate(R.layout.lista, null);
TextView textViewNomeLista = (TextView) view.findViewById(R.id.text);
textViewNomeLista.setText(tabela.getNome());
return view;
}
}
My code that works with the list
package com.example.app;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.os.Bundle;
import android.support.v7.internal.view.menu.ActionMenuView.ActionMenuChildView;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class gerenciar extends ListActivity{
boolean editar=false, adcionar=false, remover=false;
SQLiteDatabase Banco = null;
Cursor cursor;
List<Lista> tabelas = new ArrayList<Lista>();
String tabbanco="Tabela1";
TextView gerenciar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gerenciamento);
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
gerenciar=(TextView)findViewById(R.id.textViewgerenciar);
gerenciar.setText(" Escolha a tabela que deseja trabalhar.");
abrebanco();
buscardados();
List<Lista> lista = gerarlista();
final Listaadapter listasadapter = new Listaadapter(this, lista);
setListAdapter(listasadapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Lista tabela = listasadapter.getItem(position);
Intent intent = new Intent(gerenciar.this, MainActivity.class);
intent.putExtra("tabbanco", tabela.getNome());
gerenciar.this.finish();
startActivity(intent);
}
});
}
public List<Lista> gerarlista() {
//tabelas.add(criarLista("Tabela1"));
cursor.moveToLast();
int x=cursor.getCount();
while(x>0){
//nextdado();
tabelas.add(criarLista(retornadado()));
dadoanterior();
x--;
};
return tabelas;
}
public boolean dadoanterior() {
try{
cursor.moveToPrevious();
return true;
}
catch(Exception erro){
return false;
}
}
public boolean nextdado(){
try{
cursor.moveToNext();
return true;
}
catch(Exception erro){
return false;
}
}
private Lista criarLista(String nome) {
Lista tabelas = new Lista(nome);
return tabelas;
}
public boolean buscardados(){
try{
cursor = Banco.query("tabela",
new String [] {"tabelas",}
, null, null, null, null, null);
if (cursor.getCount() != 0){
cursor.moveToFirst();
}else{
String sql = "INSERT INTO tabela (tabelas) " +
"values (Tabela1) ";
Banco.execSQL(sql);
}
return true;
}
catch(Exception erro){
Exibirmensagem("BANCO", "erro ao buscar no banco: "+ erro.getMessage(), "ok");
return false;
}
}
public String retornadado(){
String dado = cursor.getString(cursor.getColumnIndex("tabelas"));
return dado;
}
public void abrebanco(){
try{
Banco = openOrCreateDatabase("banco", MODE_WORLD_WRITEABLE, null);
String sql ="CREATE TABLE IF NOT EXISTS tabela (ID INTEGER PRIMARY KEY" +
", tabelas TEXT)";
Banco.execSQL(sql);
}
catch(Exception erro){
Exibirmensagem("BANCO", "erro ao criar banco: =/"+ erro.getMessage(), "ok");
}
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if(featureId == Window.FEATURE_ACTION_BAR && menu != null){
if(menu.getClass().getSimpleName().equals("MenuBuilder")){
try{
Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
m.setAccessible(true);
m.invoke(menu, true);
} catch(NoSuchMethodException e){
} catch(Exception e){
throw new RuntimeException(e);
}
}
}
return super.onMenuOpened(featureId, menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.gerenciar, menu);
getMenuInflater().inflate(R.menu.gerenciarescondido, menu);
onMenuOpened(Window.FEATURE_ACTION_BAR, menu);
return true;
}
//seta as opções de função dos itens do menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.menuadd) {
Intent intent = new Intent(gerenciar.this, adcionartabela.class);
startActivity(intent);
gerenciar.this.finish();
return true;
}
if(id==R.id.menuremov){
AlertDialog.Builder mensagem =
new AlertDialog.Builder(gerenciar.this);
mensagem.setTitle("Atenção!");
mensagem.setMessage("Deseja realmente excluir uma tabela?" +
"\n Os dados contidos serão excluidos permanentemente!");
mensagem.setIcon(R.drawable.sair);
mensagem.setPositiveButton("Sim",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent intent = new Intent(gerenciar.this, excluirtabela.class);
startActivity(intent);
gerenciar.this.finish();
}});
mensagem.setNegativeButton("Não",null);
mensagem.show();
return true;
}
if (id == R.id.menusair) {
AlertDialog.Builder mensagem =
new AlertDialog.Builder(gerenciar.this);
mensagem.setTitle("Atenção!");
mensagem.setMessage("Deseja realmente sair?");
mensagem.setIcon(R.drawable.sair);
mensagem.setPositiveButton("Sim",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
gerenciar.this.finish();
}});
mensagem.setNegativeButton("Não",null);
mensagem.show();
return true;
}
/* if (id == R.id.menuexportar) {
Intent intent = new Intent(gerenciar.this, exportararquivo.class);
//intent.putExtra("tabbanco", tabela.getNome());
startActivity(intent);
gerenciar.this.finish();
return true;
}
if (id == R.id.menuimportar) {
Intent intent = new Intent(gerenciar.this, importararquivo.class);
//intent.putExtra("tabbanco", tabela.getNome());
startActivity(intent);
//gerenciar.this.finish();
return true;
}*/
return super.onOptionsItemSelected(item);
}
public void Exibirmensagem (String titulo,
String texto, String button)
{
AlertDialog.Builder mensagem =
new AlertDialog.Builder(gerenciar.this);
mensagem.setTitle(titulo);
mensagem.setMessage(texto);
mensagem.setNeutralButton(button,null);
mensagem.show();
}
}
Joannis is using the
appcompat
to use Actionbar? Se for infelizmente o
Listactivitynão tem relação com ele, logo não tem ´ActionBar
. What you can do is create a subclass ofActionBarActivity
and include the facilitiesListActivity
looking at the source code: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/4.3_r1/android/app/ListActivity.java.– Wakim
Yeah that’s right, how do I do it?
– Joannis
I can put together an answer tonight, but the idea is to copy the code from
ListActivity
and make a subclass ofActionBarActivity
, to have the functionalities ofListActivity
in theActionBarActivity
.– Wakim
I understood the idea, I just don’t know how to create a subclass, nor how to use it, well I’ll try if I get put here the answer, if I don’t thank you very much for your help.vlw
– Joannis
You don’t have to go to the point of copying source code from
ListActivity
(although it is a small class), doing something like this is enough: http://stackoverflow.com/questions/2242136/how-can-i-implementa-listview-without-listactivity-use-only-activity– Piovezan
Yes, copying the code is not going to be simple. It has a method that
ActionBarActivity
left asfinal
but that theListActivity
usa... I think the idea of @Piovezan is simpler.– Wakim
@wakim can you give me a hand with that? I put it aside for a while and now it’s picking up, (just missing this) I looked at the Piovezan link but I didn’t get it right. I will post my codes in the question.
– Joannis
@Joannis, you need to change the superclass of
ListActivity
forActionBarActivity
and make the right adjustments. I can prepare an answer later, at the moment I’m kind of stuck at work...– Wakim
Okay, I’ll try to do it here, I’ll see what I can do, I’ll post my advance.
– Joannis