删除操作的ToolBar错误

时间:2015-11-27 18:35:44

标签: java android button action

enter image description here

按“注释”(cardview)我有这个错误。 删除操作应该在工具栏上,而不是它。 你能帮助我吗? 由于我不能在这里发布活动,我发布网址: https://github.com/Heromine/tempapp1/blob/master/MainActivity.java 抱歉 如果您需要更多信息,请询问。谢谢你的帮助

public class MainActivity extends RoboActionBarActivity
    implements NavigationView.OnNavigationItemSelectedListener
    {
private static final int NEW_NOTE_RESULT_CODE = 4;
private static final int EDIT_NOTE_RESULT_CODE = 5;
@InjectView(android.R.id.empty)   private TextView emptyListTextView;
@InjectView(android.R.id.list)    private ListView listView;
@InjectView(R.id.fab) private FloatingActionButton addNoteButton;

@Inject private NoteDAO noteDAO;

private ArrayList<Integer> selectedPositions;
private ArrayList<NotesAdapter.NoteViewWrapper> notesData;
private NotesAdapter listAdapter;
private ActionMode.Callback actionModeCallback;
private ActionMode actionMode;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar); //       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Snackbar.make(view, "Nota in salvataggio...", Snackbar.LENGTH_LONG)
              //      .setAction("Action", null).show();

                // Crear una nota nueva
                startActivityForResult(EditNoteActivity.buildIntent(MainActivity.this), NEW_NOTE_RESULT_CODE);
        }

    });
    selectedPositions = new ArrayList<>();
    setupNotesAdapter();
    setupActionModeCallback();
    setListOnItemClickListenersWhenNoActionMode();
    updateView();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
           this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    SharedPreferences settings = getSharedPreferences("prefs", 0);
    boolean firstRun = settings.getBoolean("firstRun", true);
     if ( firstRun )
    {  // here run your first-time instructions, for example :
        Intent intent = new Intent(this, MyIntro.class);
        startActivity(intent);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("firstRun", false);
        editor.commit();
    }

}   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.action_settings:
            startActivity(new Intent("android.intent.action.SettingsActivity"));
            return true;

        case R.id.action_donate:
            Snackbar.make(this.findViewById(android.R.id.content), "Questo contenuto non è ancora disponibile", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            //startActivity(new Intent("android.intent.action.DonateActivity"));
            return true;

        default:
            return super.onOptionsItemSelected(item);

    }


}@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}



@SuppressWarnings("StatementWithEmptyBody")

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camara) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {
        Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=notes.service.com.servicenotes"));
        startActivity(i2);

    } else if (id == R.id.action_bug){
        Intent intent = new Intent(this, Gitty.class);
        startActivity(intent);
        return true;

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == NEW_NOTE_RESULT_CODE) {
        if (resultCode == RESULT_OK) addNote(data);
    }
    if (requestCode == EDIT_NOTE_RESULT_CODE) {
        if (resultCode == RESULT_OK) updateNote(data);
    }

    super.onActivityResult(requestCode, resultCode, data);
}

/** Crea la llamada al modo contextual. */
private void setupActionModeCallback() {
    actionModeCallback = new ActionMode.Callback() {

        /** {@inheritDoc} */
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            setListOnItemClickListenersWhenActionMode();
            // inflar menu contextual
            mode.getMenuInflater().inflate(R.menu.context_note, menu);
            return true;
        }

        /** {@inheritDoc} */
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Nada
            return false;
        }

        /** {@inheritDoc} */
        @Override
        public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                // borrar notas solo si hay notas a borrar; sino se acaba el modo contextual.
                case R.id.action_delete:
                    if (!selectedPositions.isEmpty()) {
                        new AlertDialog.Builder(MainActivity.this)
                                .setMessage(getString(R.string.delete_notes_alert, selectedPositions.size()))
                                .setNegativeButton(android.R.string.no, null)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        deleteNotes(selectedPositions);
                                        mode.finish();
                                    }
                                })
                                .show();
                    } else mode.finish();
                    return true;
                default:
                    return false;
            }
        }

        /** {@inheritDoc} */
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // Regresar al modo normal
            setListOnItemClickListenersWhenNoActionMode();
            resetSelectedListItems();
        }
    };
}

/** Inicializa el adaptador de notas. */
private void setupNotesAdapter() {
    notesData = new ArrayList<>();
    for (Note note : noteDAO.fetchAll()) {
        NotesAdapter.NoteViewWrapper noteViewWrapper = new NotesAdapter.NoteViewWrapper(note);
        notesData.add(noteViewWrapper);
    }
    listAdapter = new NotesAdapter(notesData);
    listView.setAdapter(listAdapter);
}

/** Actualiza la vista de esta actividad cuando hay notas o no hay notas. */
private void updateView() {
    if (notesData.isEmpty()) { // Mostrar mensaje
        listView.setVisibility(View.GONE);
        emptyListTextView.setVisibility(View.VISIBLE);
    } else { // Mostrar lista
        listView.setVisibility(View.VISIBLE);
        emptyListTextView.setVisibility(View.GONE);
    }
}

/**
 * Agrega una nota a lista y la fuente de datos.
 *
 * @param data los datos de la actividad de edición de notas.
 */
private void addNote(Intent data) {
    Note note = EditNoteActivity.getExtraNote(data);
    noteDAO.insert(note);
    NotesAdapter.NoteViewWrapper noteViewWrapper = new NotesAdapter.NoteViewWrapper(note);
    notesData.add(noteViewWrapper);
    updateView();
    listAdapter.notifyDataSetChanged();
}
/**
 * Borra notas de la lista y de la fuente de datos.
 *
 * @param selectedPositions las posiciones de las notas en la lista.
 */
private void deleteNotes(ArrayList<Integer> selectedPositions) {
    ArrayList<NotesAdapter.NoteViewWrapper> toRemoveList = new ArrayList<>(selectedPositions.size());
    // Primero borra de la base de datos
    for (int position : selectedPositions) {
        NotesAdapter.NoteViewWrapper noteViewWrapper = notesData.get(position);
        toRemoveList.add(noteViewWrapper);
        noteDAO.delete(noteViewWrapper.getNote());
    }
    // Y luego de la vista (no al mismo tiempo porque pierdo las posiciones que hay que borrar)
    for (NotesAdapter.NoteViewWrapper noteToRemove : toRemoveList) notesData.remove(noteToRemove);
    updateView();
    listAdapter.notifyDataSetChanged();
}

/**
 * Actualiza una nota en la lista y la fuente de datos.
 *
 * @param data los datos de la actividad de edición de notas.
 */
private void updateNote(Intent data) {
    Note updatedNote = ViewNoteActivity.getExtraUpdatedNote(data);
    noteDAO.update(updatedNote);
    for (NotesAdapter.NoteViewWrapper noteViewWrapper : notesData) {
        // Buscar la nota vieja para actulizarla en la vista
        if (noteViewWrapper.getNote().getId().equals(updatedNote.getId())) {
            noteViewWrapper.getNote().setTitle(updatedNote.getTitle());
            noteViewWrapper.getNote().setContent(updatedNote.getContent());
            noteViewWrapper.getNote().setUpdatedAt(updatedNote.getUpdatedAt());
        }
    }
    listAdapter.notifyDataSetChanged();
}

/** Reinicia las notas seleccionadas a no seleccionadas y limpia la lista de seleccionados. */
private void resetSelectedListItems() {
    for (NotesAdapter.NoteViewWrapper noteViewWrapper : notesData) noteViewWrapper.setSelected(false);
    selectedPositions.clear();
    listAdapter.notifyDataSetChanged();
}

/**
 * Inicializa las acciones de la lista al hacer click en sus items cuando NO esta activo el
 * modo contextual.
 */
private void setListOnItemClickListenersWhenNoActionMode() {
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Ver la nota al hacer click
            startActivityForResult(ViewNoteActivity.buildIntent(MainActivity.this, notesData.get(position).getNote()), EDIT_NOTE_RESULT_CODE);
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            // Iniciar modo contextual para selección de items
            notesData.get(position).setSelected(true);
            listAdapter.notifyDataSetChanged();
            selectedPositions.add(position);
            actionMode = startSupportActionMode(actionModeCallback);
            actionMode.setTitle(String.valueOf(selectedPositions.size()));
            return true;
        }
    });
}

/**
 * Inicializa las acciones de la lista al hacer click en sus items cuando esta activo el menu
 * contextual.
 */
private void setListOnItemClickListenersWhenActionMode() {
    listView.setOnItemLongClickListener(null);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Agregar items a la lista de seleccionados y cambiarles el fondo.
            // Si se deseleccionan todos los items, se acaba el modo contextual
            if (selectedPositions.contains(position)) {
                selectedPositions.remove((Object) position); // no quiero el índice sino el objeto
                if (selectedPositions.isEmpty()) actionMode.finish();
                else {
                    actionMode.setTitle(String.valueOf(selectedPositions.size()));
                    notesData.get(position).setSelected(false);
                    listAdapter.notifyDataSetChanged();
                }
            } else {
                notesData.get(position).setSelected(true);
                listAdapter.notifyDataSetChanged();
                selectedPositions.add(position);
                actionMode.setTitle(String.valueOf(selectedPositions.size()));
            }
        }
    });
}

}

2 个答案:

答案 0 :(得分:1)

在清单中,您将声明要使用“MyAppTheme”作为样式。

<application
        ..
        android:theme="@style/MyAppTheme"
        ..>

请注意,您需要删除manifest中.MainActivity的类似行。目前你关闭标签和清单结构不干净。

现在最重要的是:在样式中定义新样式如下:

<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="windowActionModeOverlay">true</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

</style>

这将是解决方案,它将确保ActionMode项目不会“推”下工具栏。


更重要的事情:

  • 本地化所有字符串(不要硬编码一半用英文,一半是意大利语)
  • 你最好的朋友是 ctrl + alt + L on Win或 cmd + alt mac上的 + L 。这个快捷方式将自动格式化类和xmls中的代码(目前代码中的代码很难阅读,因为没有对齐而且看起来很乱)
  • 考虑使用Dagger2或更简单,但功能较弱的ButterKnife而不是RoboJuice。如果你没有从其他人那里接受这个项目(就像它看起来那样)你会知道我在说什么
  • 你不应该硬编码api密钥并在github上发布它们。它不安全,任何看到这些的人都可以对您的帐户做任何事情。我应该大胆一点。
  • 如果您不想免费提供应用程序(通过代码似乎您没有计划但是提交了apk),您不应该将apk提交到repo。
  • 一般来说,您需要组织更好的Android Studio项目并注意您提交的内容。现在那个回购中有很多混乱
  • 不要盲目使用其他人不理解的代码。

答案 1 :(得分:0)

假设您的主题与以下内容类似:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

尝试以下方法:

在您宣布活动的清单中,将活动的主题声明为AppTheme.NoActionBar ......

    <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar">

这将摆脱顶部的第二个ActionBar。如果您想要ActionBar,那么您可以尝试以下方法:

toolbar.inflateMenu(R.menu.main);
创建工具栏后立即

如果有效,请告诉我。