【问题标题】:Change text dynamically for Android Actionbar Button为 Android 操作栏按钮动态更改文本
【发布时间】:2012-11-01 18:21:12
【问题描述】:

我有一个包含两个项目的操作栏(使用 actionbarsherlock)。其中之一是用户在我的应用程序中收集的点数。当点数发生变化时,我想更改此操作栏按钮。

我不知道如何设置该按钮的 TextView。我该怎么做才能通过代码进行设置?

【问题讨论】:

    标签: android android-actionbar actionbarsherlock


    【解决方案1】:

    ActionBar 项目来自选项菜单,当显示在栏上时呈现为按钮。如果不提供图标,则将选项 MenuItem 的标题用作按钮的标题,

    因此,除非您使用自定义视图,并且您只是使用菜单项标题作为分数指示器,否则您可以在 onPrepareOptionsMenu() 中更改它。当你需要更新时,拨打invalidateOptionsMenu(),onPrepareOptionsMenu会为你调用。

    例如

    //user scores some points
    mUserScore += points;
    invalidateOptionsMenu();
    

    然后在回调中:

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        MenuItem score = menu.findItem(R.id.score_menu_item);
        score.setTitle(String.valueOf(mUserScore));
    }
    

    【讨论】:

      【解决方案2】:

      首先你没有设置“按钮的TextView”,因为按钮扩展了TextView,你设置了按钮本身的文本。您可以在活动的onCreate() 中尝试通过以下方式执行此操作:

      //I suppose you create custom ActionBar like this
      final View addView = getActivity().getLayoutInflater().inflate(R.layout.my_action_bar, null);
      bar.setCustomView(addView);
      button=(Button)addView.findViewById(R.id.button);
      button.setText("Whatever");
      

      如果您使用菜单项,那么您应该尝试这种方法:

      getSupportMenuInflater().inflate(R.menu.activitymenu, menu);
      MenuItem menuItem=menu.findItem(R.id.menuSearch);
      

      还可以尝试查看hereherehere。应该会有帮助。

      【讨论】:

      • 所以我不知道这是否适合我的情况。我有这个 actionBar=getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);对于操作栏,然后是菜单 xml 中已有的一些项目。我不知道如何访问它们。
      【解决方案3】:

      这段代码对我有用

      actionBar.setCustomView(R.layout.my_action_bar);
      button=(Button)actionBar.getCustomView().findViewById(R.id.button);
      button.setText("text");
      

      【讨论】:

        猜你喜欢
        • 2013-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        • 1970-01-01
        • 2016-03-02
        相关资源
        最近更新 更多