-1

I want to change textView(in mainActivity)'s property like textSize, or textColor.

Then I tried to use it at setting activity.

View view = getLayoutInflater().inflate(R.layout.activity_main, null);
readTextView = view.findViewById(R.id.textView);

And It doesn't work.

Also, I tried to How to update a TextView of an activity from another class this answer. But isn't it can only change the text? If I need to change much property, I have to make a method in my activity.

SunSpike
  • 31
  • 5

2 Answers2

0

Android access main activity variables from another class

I referenced this answer.

  1. Declare public static the resource which you want to change.
  2. Use like [Your Activity].[The Resource] at your setting Activity.

I really sorry to question like this... Sorry.

SunSpike
  • 31
  • 5
0

You must not using a public variable as a mechanism to update your View inside an activity because of the following:

  • You can't ensure that the activity is always exist. There is a probability that the activity is killed by system because of error or you're finishing the activity.

  • You're coupling your activity with another class. So, each time you're changing the activity there is probability that your change propagate to another class. This probably will introduce bugs to multiple classes.

You better strictly access the View from another class by sending only the view as a parameter. For example, if you have the following activity:

public class YourActivity extends AppCompatActivity {
  private TextView mTvName;

  ...
} 

to change the properties of mTvName, you need to create something like this:

public class TextChanger {
  public static void maximizeTextSize(TextView tv) {
    tv.setTextSize(30);
  }
}

then you can use it in your Activity:

TextChanger.maximizeTextSize(mTvName);

If you want to update the TextView from another Activity, you can use startActivityForResult for starting the another Activity. Then you need to receive the result to change your TextView by overriding onActivityResult in your activity.

In case you need to update the TextView without any coupling with another class or Activity, you can use Event Bus mechanism. You can use EventBus library.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96