Hossam Oukli
Hossam Oukli

Reputation: 1296

Modify the value of TextView from an external class

I have an activity myActivity that contains one TextView myTv, and another Class myClass with a single method modifyTv.

How can i modify the value of myTv using the modifyTv method ?

class myActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myClass myc = new myClass();
    myc.modifyTv();// this line of code must be able to modify myTv value.

}
}

Upvotes: 0

Views: 546

Answers (3)

Phil
Phil

Reputation: 36289

You have several options:

1. Pass more info to the constructor. For example, Context or myTv. For example:

public class MyClass {
    Context context;
    public MyClass(Context context) {
        this.context = context;
    }
    public void modifyTv() {
        TextView tv = (TextView) context.findViewById(R.id.myTv);
        tv.setText("Foobar");
    }
}

Then just call:

MyClass m = new MyClass(this);
m.modifyTv();

2. Pass more info to the modifyTv() method.

public class MyClass {

    public void modifyTv(TextView tv) {
        tv.setText("Foobar");
    }
}

Then just call:

MyClass m = new MyClass();
m.modifyTv((TextView) findViewById(R.id.tv));

3. Other, more complicated ways that don't make much sense.

Upvotes: 1

edthethird
edthethird

Reputation: 6263

well, you could do:

myc.modifyTv(myTextView);

and just pass the TextView you want to modify as a parameter.

Upvotes: 1

Axxiss
Axxiss

Reputation: 4789

In 'myClass' you will need a reference to your activity so you can call

activity.findViewById(R.id.text_id)

You can pass the activity in the constructor or creating let say setCurrentActivity method in myClass

Or, even easier have a reference to the TextView itself.

Upvotes: 1

Related Questions