动态改变的TextView的片段(公共无效而processMessage)(Dynamically

2019-10-29 03:18发布

我正在寻找一种方式来创建一个聊天片段。 所以基本上,我试图让一个片段动态。 作为第一步,我想更新一个TextView,我有能够显示收到的消息。 我使用XMPP作为客户端,我通过下面的函数接收消息:

        @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));
        }

任何有关动态更新的片段一个TextView帮助表示赞赏。

谢谢

马克斯

Answer 1:

举例MyFragment ,让文字更新:

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);
    }
}

的实施例Activity保持所述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!");
            }
        }
    }
}


Answer 2:

在而processMessage()函数,你可以做getView().findViewById(id_of_text_view);

getView()返回在创建视图onCreateView()

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



文章来源: Dynamically change TextView in Fragment (public void processMessage)