Reputation: 425
Hello guys right now I'm working on an app in which there are many quotes, in a TextView
and I want to change the size of TextView
on button click, like if Small button is clicked then the TextView
should become small, if Large is clicked it should be large, etc. But each time I press the Button
app force closes! What's the problem? Here's OnClickListener
for the Button
:
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: The TextView
and the Button
are in different Activities
.
Upvotes: 0
Views: 473
Reputation: 12365
There is no way to change the TextView
size by Button
from one Activity
in other Activity
. You will get NullPointerException
because the findViewById method will not find view and will return null. You should use SharedPreferences
. You should save text size value when you click Button
and read it in the second Activity
.
In your setting 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();
}
});
In your activity where you have TextView
TextView tv = (TextView)findViewById(R.id.quotes);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourActivity.this.getBaseContext());
tv.setTextSize(sharedPreferences.getFloat("FONT_SIZE", 13/*DEFAULT VALUE*/));
Upvotes: 2