2012-02-09 69 views
0

这是我的代码(编辑):改变字体样式动态

公共类主要活动扩展
{

TextView txt; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{  
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Button b=(Button) findViewById(R.id.button1); 
     txt = (TextView) findViewById(R.id.textView1); 

     b.setOnClickListener(new Button.OnClickListener() 
     { 

     public void onClick(View v) 
     { 
      Intent intent= new Intent(Main.this,Preference.class); 
      startActivity(intent); 
     } 
     }); 

}  

public void onResume() 
{ 
    super.onResume(); 
    Toast.makeText(this, "onResume", Toast.LENGTH_LONG).show(); 
    SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this); 
    boolean first=myPreference.getBoolean("first", true); 
    if(first) 
    { 

    Typeface font=Typeface.MONOSPACE; 
    txt.setTypeface(font); 
    } 
} 

}

main.xml中,在这里有TextView的其文本样式需要更改。现在不需要重新启动应用程序生效复选框首选项的上一个问题。但问题是,当我取消选中复选框偏好它不会进入其默认状态。是吗?任何人都可以帮我在代码中弄错什么?

回答

1

我认为你正在使用的喜好来改变字体?

您选中了一个框并希望字体根据是否被选中来更改?

当您在更改首选项后返回到您的活动时,这不会导致您的onCreate()方法运行,因为该活动已存在于您的后退堆栈中,并且正在重新显示。

您应该将字体更改代码放在onResume()方法中或使用startActivityForResult方法并处理其中的偏好设置。

更新:

if (first) { 
    txt.setTypeface(Typeface.MONOSPACE); 
} else { 
    txt.setTypeface(Typeface.SERIF); 
} 
1

尝试调用txt.requestLayout()。这将重新绘制视图。

+0

我已经包括它的代码。 – Tejaswini 2012-02-09 07:04:02

+0

看到更新的响应 – 2012-02-09 07:16:05

+0

尝试txt.requestLayout但仍然输出相同。 – Tejaswini 2012-02-09 07:37:10