Dynamically change TextView in Fragment (public vo

2019-08-30 08:17发布

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

2条回答
Emotional °昔
2楼-- · 2019-08-30 08:44

In the processMessage() function, you can do getView().findViewById(id_of_text_view);

getView() returns the View created in onCreateView()

http://developer.android.com/reference/android/app/Fragment.html#getView%28%29

查看更多
聊天终结者
3楼-- · 2019-08-30 08:45

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!");
            }
        }
    }
}
查看更多
登录 后发表回答