0

我正在寻找一种创建聊天片段的方法。所以基本上我正在尝试使片段动态化。作为第一步,我试图更新一个文本视图,我必须显示收到的消息。我使用 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));
        }

任何有关在片段中动态更新文本视图的帮助表示赞赏。

谢谢

最大限度

4

2 回答 2

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!");
            }
        }
    }
}
于 2013-05-03T16:33:53.060 回答
1

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

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

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

于 2013-05-03T17:58:34.827 回答