Add buttons to the bar action when using Listactivity?

Asked

Viewed 1,274 times

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.

como eu queria que ficasse

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



}
  • 1

    Joannis is using the appcompat to use Actionbar? Se for infelizmente o Listactivity não tem relação com ele, logo não tem ´ActionBar. What you can do is create a subclass of ActionBarActivity and include the facilities ListActivity looking at the source code: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/4.3_r1/android/app/ListActivity.java.

  • Yeah that’s right, how do I do it?

  • I can put together an answer tonight, but the idea is to copy the code from ListActivity and make a subclass of ActionBarActivity, to have the functionalities of ListActivity in the ActionBarActivity.

  • 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

  • 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

  • Yes, copying the code is not going to be simple. It has a method that ActionBarActivity left as final but that the ListActivity usa... I think the idea of @Piovezan is simpler.

  • @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, you need to change the superclass of ListActivity for ActionBarActivity and make the right adjustments. I can prepare an answer later, at the moment I’m kind of stuck at work...

  • Okay, I’ll try to do it here, I’ll see what I can do, I’ll post my advance.

Show 4 more comments

1 answer

1


As I suggested earlier, the idea is to create a class that inherits from ActionBarActivity but which has the support methods of the class ListActivity.

The class would be this:

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

}

The maximum code that the ListActivity provides, but only one method is left out. Because the ActionBarActivity writes about the method onContentChanged of adds the modifier final, so it is not possible to write it in the created class.

But by its use, the ListActionBarActivity must meet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.