【问题标题】:Android AlertDialog with dynamically changing textSize in contextmenuAndroid AlertDialog 在上下文菜单中动态更改 textSize
【发布时间】:2011-09-18 12:18:26
【问题描述】:

在一个活动中,我有两个文本视图。在上下文菜单中,我可以选择更改其中一个文本视图的文本大小。我试过这样的东西..

       public boolean onOptionsItemSelected(MenuItem item){
          switch (item.getItemId()){
                  case R.id.menutextSize:
                    final CharSequence[] items = {"Normal","Large","Larger"};
                    AlertDialog.Builder builder = new      

           AlertDialog.Builder(this);
                    builder.setTitle("Select TextSize");
                    builder.setSingleChoiceItems(items, -1, 
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            Toast.makeText(getApplicationContext(), items[item],
                                    Toast.LENGTH_SHORT).show();
                        }
                    });

                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            int textSize = (int)mBodyText.getTextSize();  
                            if (items[whichButton] == "Normal")    
                            {
                                mTextv.setTextSize(12);
                            }
                            if (items[whichButton] == "Large")    
                            {
                                mTextv.setTextSize(14);
                            }
                            if (items[whichButton] == "Larger")    
                            {
                                mTextv.setTextSize(16);
                            }




                        }
                    });
                    builder.setNegativeButton("cancel", null);
                    builder.show();
                    return true;    
          }

当我点击单选按钮时,它显示“强制关闭”消息。我该如何解决这个问题? 谢谢。。

【问题讨论】:

    标签: android text-size


    【解决方案1】:

    您的应用程序崩溃,因为它试图访问 items 数组中具有负索引的元素。发生这种情况是因为以下几行:

    if (items[whichButton] == "...")
    

    如果您仔细查看DialogInterface.OnClickListener 文档,您会注意到它的onClick() 方法接受诸如BUTTON_POSITIVEBUTTON_NEUTRALBUTTON_NEGATIVE 之类的常量,它们都是负数,并且与列表项无关。

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 1970-01-01
      • 2015-03-21
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 2018-09-19
      相关资源
      最近更新 更多