单击按钮时无法更改 TextView 大小,为什么?
Unable to change TextView size on button click, why?
大家好,我现在正在开发一个应用程序,其中有很多引号,在 TextView
中,我想在单击按钮时更改 TextView
的大小,比如 Small单击按钮然后 TextView
应该变小,如果单击大它应该变大,等等。但是每次我按下 Button
应用程序强制关闭!有什么问题? Button
的 OnClickListener
:
small = (Button) findViewById(R.id.small);
small.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.quotes);
tv.setTextSize(20);
}
});
P.S: TextView
和 Button
是不同的 Activities
.
无法将 TextView
大小从一个 Activity
更改为另一个 Activity
Button
。您将得到 NullPointerException
,因为 findViewById 方法将找不到视图并且 return 为空。你应该使用 SharedPreferences
。单击 Button
并在第二个 Activity
中阅读时,应保存文本大小值。
在您的设置中 Activity:
small.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourActivity.this.getBaseContext());
sharedPreferences.edit()
.putFloat("FONT_SIZE", 22)
.apply();
}
});
在你的 activity 中你有 TextView
TextView tv = (TextView)findViewById(R.id.quotes);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourActivity.this.getBaseContext());
tv.setTextSize(sharedPreferences.getFloat("FONT_SIZE", 13/*DEFAULT VALUE*/));
大家好,我现在正在开发一个应用程序,其中有很多引号,在 TextView
中,我想在单击按钮时更改 TextView
的大小,比如 Small单击按钮然后 TextView
应该变小,如果单击大它应该变大,等等。但是每次我按下 Button
应用程序强制关闭!有什么问题? Button
的 OnClickListener
:
small = (Button) findViewById(R.id.small);
small.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.quotes);
tv.setTextSize(20);
}
});
P.S: TextView
和 Button
是不同的 Activities
.
无法将 TextView
大小从一个 Activity
更改为另一个 Activity
Button
。您将得到 NullPointerException
,因为 findViewById 方法将找不到视图并且 return 为空。你应该使用 SharedPreferences
。单击 Button
并在第二个 Activity
中阅读时,应保存文本大小值。
在您的设置中 Activity:
small.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourActivity.this.getBaseContext());
sharedPreferences.edit()
.putFloat("FONT_SIZE", 22)
.apply();
}
});
在你的 activity 中你有 TextView
TextView tv = (TextView)findViewById(R.id.quotes);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourActivity.this.getBaseContext());
tv.setTextSize(sharedPreferences.getFloat("FONT_SIZE", 13/*DEFAULT VALUE*/));