带有删除操作的工具栏错误
ToolBar bug with delete action
我按 "note"(卡片视图)时出现此错误。
删除操作应该在工具栏上,而不是在上面。
你能帮助我吗?
因为我不能 post activity 这里我 post url:
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()));
}
}
});
}
}
假设您的主题类似于以下内容:
<!-- 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>
尝试以下操作:
在您声明 activity 的清单中,将 activity 的主题声明为 AppTheme.NoActionBar...
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.NoActionBar">
这将去掉顶部的第二个 ActionBar。如果您确实想要那个 ActionBar,那么您可以尝试以下操作:
toolbar.inflateMenu(R.menu.main);
在您创建工具栏之后。
如果可行,请告诉我。
在清单中,您将声明要使用 "MyAppTheme" 作为样式。
<application
..
android:theme="@style/MyAppTheme"
..>
请注意,您需要在清单中删除 .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 项目不会 "push" 关闭工具栏。
一些更重要的事情:
- 本地化所有字符串(不要硬编码一半是英语,一半是意大利语)
- 你最好的新朋友是 ctrl+alt+L 或 cmd+alt+L 在 mac 上。此快捷方式将为您自动格式化 类 和 xml 中的代码(目前您项目中的代码很难阅读,因为没有对齐并且看起来很乱)
- 考虑使用 Dagger2 或更简单但功能较弱的 ButterKnife 代替 RoboJuice。如果你没有从别人那里得到这个项目(就像它看起来的那样)你就会明白我在说什么
- 您不应该对 api 密钥进行硬编码并在 github 上发布它们。它不安全,任何看到这些的人都可以对您的帐户进行任何操作。我应该把这个加粗。
- 如果你不想免费提供应用程序,你不应该将 apk 提交到 repo(代码看起来你没有计划但 apk 已提交)
- 一般来说,您需要更好地组织 Android Studio 项目并注意您提交的内容。现在那个 repo
里有很多乱七八糟的东西
- 不要盲目使用别人自己看不懂的代码。
我按 "note"(卡片视图)时出现此错误。 删除操作应该在工具栏上,而不是在上面。 你能帮助我吗? 因为我不能 post activity 这里我 post url: 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()));
}
}
});
}
}
假设您的主题类似于以下内容:
<!-- 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>
尝试以下操作:
在您声明 activity 的清单中,将 activity 的主题声明为 AppTheme.NoActionBar...
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.NoActionBar">
这将去掉顶部的第二个 ActionBar。如果您确实想要那个 ActionBar,那么您可以尝试以下操作:
toolbar.inflateMenu(R.menu.main);
在您创建工具栏之后。
如果可行,请告诉我。
在清单中,您将声明要使用 "MyAppTheme" 作为样式。
<application
..
android:theme="@style/MyAppTheme"
..>
请注意,您需要在清单中删除 .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 项目不会 "push" 关闭工具栏。
一些更重要的事情:
- 本地化所有字符串(不要硬编码一半是英语,一半是意大利语)
- 你最好的新朋友是 ctrl+alt+L 或 cmd+alt+L 在 mac 上。此快捷方式将为您自动格式化 类 和 xml 中的代码(目前您项目中的代码很难阅读,因为没有对齐并且看起来很乱)
- 考虑使用 Dagger2 或更简单但功能较弱的 ButterKnife 代替 RoboJuice。如果你没有从别人那里得到这个项目(就像它看起来的那样)你就会明白我在说什么
- 您不应该对 api 密钥进行硬编码并在 github 上发布它们。它不安全,任何看到这些的人都可以对您的帐户进行任何操作。我应该把这个加粗。
- 如果你不想免费提供应用程序,你不应该将 apk 提交到 repo(代码看起来你没有计划但 apk 已提交)
- 一般来说,您需要更好地组织 Android Studio 项目并注意您提交的内容。现在那个 repo 里有很多乱七八糟的东西
- 不要盲目使用别人自己看不懂的代码。