1

Bom tenho uma aplicação que gostaria de manter o formato padrão em todas as telas, eu tenho um menu de acesso rápido com alguns itens na action bar, e outro completo na opção menu.

O problema é que como eu estou usando o ListActivity isso não esta funcionando. não entendo muito bem essa parte de extensões, se alguém tiver um bom material que explica, em português por favor, eu agradeço.

como eu queria que ficasse

Meu código XML do menu:

<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>

Meu código de inflater 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);
}

Meu código 'lista'

        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;
        }
    }

Meu código 'lista 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;
        }
    }

Meu código que trabalha com a lista

    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();
    }



}
9
  • 1
    Joannis está usando o appcompat para utilizar a ´ActionBar? Se for infelizmente o ListActivity` não tem relação com ele, logo não tem ´ActionBar. O que você pode fazer é criar uma subclasse do ActionBarActivity` e incluir as facilidades que o ListActivity trás, olhando o código fonte: grepcode.com/file/repository.grepcode.com/java/ext/….
    – Wakim
    28/10/2014 às 11:04
  • sim é isso mesmo, como eu faço isso?
    – Joannis
    28/10/2014 às 11:47
  • Posso montar uma resposta a noite, mas a ideia é copiar o código do ListActivity e fazer uma subclasse de ActionBarActivity, para se ter as funcionalidades do ListActivity no ActionBarActivity.
    – Wakim
    28/10/2014 às 12:00
  • eu entendi a ideia, só não sei como criar uma subclasse, nem como usá-la, bom vou tentar se eu conseguir posto aqui a resposta, se não agradeço muito sua ajuda.vlw
    – Joannis
    28/10/2014 às 12:04
  • Não precisa chegar ao ponto de copiar código-fonte de ListActivity (apesar de ser uma classe pequena), só fazer algo assim já é suficiente: stackoverflow.com/questions/2242136/…
    – Piovezan
    28/10/2014 às 12:22

1 Resposta 1

1

Como sugeri anteriormente, a ideia é criar uma classe que herde de ActionBarActivity mas que tenha os métodos de suporte da classe ListActivity.

A classe seria essa:

public class ListActionBarActivity extends ActionBarActivity {

    /**
     * This field should be made private, so it is hidden from the SDK.
     * {@hide}
     */
    protected ListAdapter mAdapter;
    /**
     * This field should be made private, so it is hidden from the SDK.
     * {@hide}
     */
    protected ListView mList;

    private Handler mHandler = new Handler();

    private Runnable mRequestFocus = new Runnable() {
            public void run() {
                    mList.focusableViewAvailable(mList);
            }
    };

    /**
     * This method will be called when an item in the list is selected.
     * Subclasses should override. Subclasses can call
     * getListView().getItemAtPosition(position) if they need to access the
     * data associated with the selected item.
     *
     * @param l The ListView where the click happened
     * @param v The view that was clicked within the ListView
     * @param position The position of the view in the list
     * @param id The row id of the item that was clicked
     */
    protected void onListItemClick(ListView l, View v, int position, long id) {
    }

    /**
     * Ensures the list view has been created before Activity restores all
     * of the view states.
     *
     *@see android.app.Activity#onRestoreInstanceState(android.os.Bundle)
     */
    @Override
    protected void onRestoreInstanceState(Bundle state) {
            ensureList();
            super.onRestoreInstanceState(state);
    }

    /**
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
            mHandler.removeCallbacks(mRequestFocus);
            super.onDestroy();
    }

    /**
     * Provide the cursor for the list view.
     */
    public void setListAdapter(ListAdapter adapter) {
            synchronized (this) {
                    ensureList();
                    mAdapter = adapter;
                    mList.setAdapter(adapter);
            }
    }

    /**
     * Set the currently selected list item to the specified
     * position with the adapter's data
     *
     * @param position
     */
    public void setSelection(int position) {
            mList.setSelection(position);
    }

    /**
     * Get the position of the currently selected list item.
     */
    public int getSelectedItemPosition() {
            return mList.getSelectedItemPosition();
    }

    /**
     * Get the cursor row ID of the currently selected list item.
     */
    public long getSelectedItemId() {
            return mList.getSelectedItemId();
    }

    /**
     * Get the activity's list view widget.
     */
    public ListView getListView() {
            ensureList();
            return mList;
    }

    /**
     * Get the ListAdapter associated with this activity's ListView.
     */
    public ListAdapter getListAdapter() {
            return mAdapter;
    }

    private void ensureList() {
            if (mList != null) {
                    return;
            }
            setContentView(com.android.internal.R.layout.list_content_simple);

    }

    private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                    onListItemClick((ListView)parent, v, position, id);
            }
    };

}

Foi preservado o máximo do código que a ListActivity provê, porém apenas um método ficou de fora. Porque a ActionBarActivity sobreescreve o método onContentChanged de adiciona o modificador final, logo não é possível sobreescrevê-lo na classe criada.

Mas pelo seu uso, a ListActionBarActivity deve atender.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .