1

I'm trying to setText a new value to my TextView from a non activity class by inflating the layout where the textview is, but I'm still unsuccessful though I'm able to getText the current value of the TV. Here's the code:

LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.target_details, null);

TextView val = (TextView) view.findViewById(R.id.val);

Not sure if I'm doing it properly.

UPDATE: I used Kay's answer with added code below. It's now working.

((Activity)mContext).runOnUiThread(new Runnable(){
        @Override
        public void run(){
            //settext here
        }
    });
user3360031
  • 627
  • 4
  • 13
  • 21

2 Answers2

3

You want to set text for TextView from non activity class

You can do it in 2 ways.
1. Pass your activity while initiating your Non-Activity class and use that while setting text to TextView.

public class YourClass(){
     Activity a;
     public YourClass(Activity activity){
           this.a=activity;
     }
}

2.You can pass the Activity to the method which will set text

public static void displayText(Activity activity, int id, String text) {
    TextView tv = (TextView) activity.findViewById(id);
    tv.setText(text);
}

Ex: displayText(YourActivity.this,R.id.your_text_view,"Text you want to display");

Sai Phani
  • 462
  • 3
  • 6
1

Not such a good idea to create new objects in the adapter/non-activity class. There must already be one object of TextView class in the Activity.

If its necessary to change text from the other class you can make TextView static in the Activity and access it from the adapter like

Activity:-

 Static TextView val = (TextView) view.findViewById(R.id.val);

Adapter:-

   MyActivity.val.setText("some txt");
Karan
  • 2,120
  • 15
  • 27