2011-09-18 40 views
0

在活动中,我有两个文本视图。在上下文菜单中,我可以选择更改其中一个文本视图的文本大小。我试过这样的事情..Android AlertDialog在contextmenu中动态更改textSize

 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;  
      } 

当我在显示“强制关闭”消息时,在单选按钮中出现问题。我该如何解决这个问题? 谢谢..

回答

1

您的应用崩溃,因为它试图访问items阵列中具有负索引的元素。这是因为这些行:

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

如果你仔细看DialogInterface.OnClickListener文档中,你会发现,它的onClick()方法接受这样的常量为BUTTON_POSITIVEBUTTON_NEUTRALBUTTON_NEGATIVE所有为负,而没有连接到列表项。