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
}
});
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");
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.