动态改变字体样式

时间:2012-02-09 06:54:46

标签: android checkboxpreference

这是我的代码(编辑):

公共类Main扩展活动
{

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,其文本样式需要更改。以前的问题现在不需要重新启动应用程序生效复选框首选项。但问题是当我取消选中复选框时,它不会进入默认状态。所以?可以帮我解决代码中的错误吗?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

试试这个:Using Custom Fonts

答案 2 :(得分:1)

我认为您使用首选项来更改字体?

您选中一个方框并期望字体根据是否被选中而更改?

更改首选项后返回活动时,这不会导致onCreate()方法运行,因为活动已存在于后台堆栈中,只是重新显示。

您应该将字体更改代码放在onResume()方法中,或者使用startActivityForResult方法并在那里处理首选项的关闭。

更新

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