1.写主布局文件,有一个输入框,发送按钮,用来放Fragment的LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#00ff00"/>
2.主逻辑代码文件中:发送数据
package com.day12_activitytofragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText text;
Button send;
··// FragmentManager管理对象
FragmentManager fm;
@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(EditText) findViewById(R.id.text);
send=(Button) findViewById(R.id.send);
fm=getFragmentManager();
//得到事务
FragmentTransaction shiwu = fm.beginTransaction();
//将MyFragment()放到LinearLayout并加到事务中
shiwu.add(R.id.myfra,new MyFragment());
//提交事务
shiwu.commit();
}
@SuppressLint("NewApi")
public void click(View v)
{
//获取输入的内容
String content = text.getText().toString();
//创建一个Bundle并将要发送的数据放进去
Bundle bundle=new Bundle();
bundle.putString("mes", content);
MyFragment mf=new MyFragment();
//将bundle绑定到MyFragment的对象上
mf.setArguments(bundle);
FragmentTransaction shiwu =fm.beginTransaction();
shiwu.replace(R.id.myfra, mf);
shiwu.commit();
}
}
3.创建一个布局文件fragement.xml,TextView控件用来接收Activity传过来的值
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff0000">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#0000ff"
android:textSize="30sp"/>
4.创建一个.java文件Fragment1.java,并将fragment.xml布局文件加载进去和接收数据
package com.day12_activitytofragment;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@SuppressLint("NewApi")
public class MyFragment extends Fragment{
TextView tv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.myfragment,container,false);
tv=(TextView) view.findViewById(R.id.tv);
//接收数据
Bundle bundle=getArguments();
if(bundle!=null)
{
String data = bundle.getString("mes");
tv.setText(data);
}
return view;
}
}