Max Max - 1 month ago 14
Android Question

Dynamically change TextView in Fragment (public void processMessage)

I am looking for a way to create a chat fragment. So basically I am trying to make a fragment dynamic. As a first step I am trying to update a textview which I have to display messages received. I am using XMPP as a client and I am receiving message through the following function:

@Override
public void processMessage(Chat arg0, org.jivesoftware.smack.packet.Message message) {

// TODO Auto-generated method stub
String from = message.getFrom();
String body = message.getBody();
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
text.setText(String.format("'%1$s' from %2$s", body, from));
}


Any help regarding dynamically updating a textview in a fragment is appreciated.

Thanks

Max

Answer

Example of MyFragment that allow text update:

public class MyFragment extends Fragment {

    TextView textView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_b, container, false);
        textView = (TextView) view.findViewById(R.id.textView1);
        return view;
    }

    public void updateTextValue(CharSequence newText) {
        textView.setText(newText);
    }
}

Example of Activity that holds the MyFragment:

public class Activity extends Activity {

    MyFragment myFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        FragmentManager manager = getFragmentManager();
        myFragment = (MyFragment) manager.findFragmentById(R.id.fragmentA);
    }

    @Override
    public void processMessage(Chat arg0, org.jivesoftware.smack.packet.Message message) {
        runOnUiThread(new Runnable() { 
            public void run() {             
                myFragment.updateTextValue("Hi fragment!");
            }
        }
    }
}