使用 SQLite 处理 Android 工具栏图标

标签 android android-layout android-toolbar android-menu

我需要提示来设置工具栏菜单。如何在 Intent 打开时自动更改工具栏图标。我正在使用 SQLite 来保存添加书签的帖子的数据。如果用户已经为该帖子添加了书签,则工具栏图标将发生变化,否则图标将保持不变。

enter image description here

让我们举个例子,在这张图片中,有一个书签按钮(星号),当我单击它时,数据将保存在书签表中。之后我关闭了那个帖子。现在我再次打开该帖子,该帖子已添加书签,但这次它们在工具栏菜单图标中发生了变化,如下所示:

enter image description here

要执行此功能,数据将从书签表加载。

在我的应用程序中,无需发布帖子并显示此工具栏。当有人点击帖子时, Intent 就会打开。该 Intent 的工具栏将用于此功能。帖子工具栏是here : /image/HWMF5.png当用户单击时,选定的图标将发生变化。提前致谢

最佳答案

找到解决方案:onCreate之前初始化一个int,如下所示:

int bkmark;

比在onCreate中在初始化工具栏之前从SQLite获取数据并检查该帖子是否已添加书签。

如果数据可用

bkmark = 1;

其他

bkmark = 0;

onCreateOptionsMenu中,我使用两个这样的菜单

@Override
public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
    if(bkmark == 0){//bkmark is not available
         getMenuInflater().inflate(R.menu.posts, menu);
    }else{//bkmark is available
         getMenuInflater().inflate(R.menu.postb, menu);
    }
    return true;
}

onOptionsItemSelected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id==R.id.bkm){
         if(bkmark == 1){
             //delete data from bookmark table here
             item.setIcon(R.drawable.ic_bookmark);//changing the icon
             bkmark = 0;
         }else{
             //insert data in bookmark table here
             item.setIcon(R.drawable.ic_bookmarked);//changing the icon
             bkmark = 1;
         }
    }
    return super.onOptionsItemSelected(item);
}

如果您正在寻找类似的东西,希望这篇文章对您有所帮助!

关于使用 SQLite 处理 Android 工具栏图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38930259/

相关文章:

android - 18 :9 aspect ratio screens in Android 的配置限定符

android - 如何去除工具栏周围的边框?

java - 安卓/Java : Inexplicably enters catch block but skips line

java - Android:从线程访问用户类时崩溃

Android Material 设计 - LinearLayout elevation

android - 如何将文本放在 CollapsingToolbarLayout 和 Toolbar 的中心?

android - CollapsingToolbarLayout 标题作为共享元素过渡

android - 针对单例 friend 的 Facebook AppRequest

android - 没有 ActionBar 的汉堡包图标没有透明操作栏

android - 使用单击事件以编程方式在android中创建按钮