1. 程式人生 > >Activity和Fragment傳值

Activity和Fragment傳值

activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
>

    <TextView
android:id="@+id/text"
android:layout_gravity="center"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" android:text="我是Activity" /> <FrameLayout android:layout_below="@+id/button" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="500dp"/> </LinearLayout
>
fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
>

    <TextView
android:id="@+id/fragment"
android:text="我是fragment"
android:layout_gravity="center" android:textSize="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/text" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" android:text="等待Activity傳送訊息" /> <Button android:id="@+id/button" android:layout_gravity="center" android:text="點選接收Activity訊息" android:layout_centerInParent="true" android:textSize="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity {

    Fragment fragment;
    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragment=new Fragment();


        Bundle bundle = new Bundle();
        bundle.putString("mess","我是傳過來的");
        fragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().add(R.id.frament,fragment).commit();
    }
}

Frament

public class Fragment extends android.support.v4.app.Fragment {

    TextView textView;
    Button button;
    Bundle bundle;

    @Nullable
    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment,container,false);

        textView=(TextView) view.findViewById(R.id.text);
        button=(Button) view.findViewById(R.id.but);

        bundle=this.getArguments();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {
                textView.setText(bundle.getString("mess"));
            }
        });
        return view;
    }
}