1. 程式人生 > >Fragment傳值

Fragment傳值

***Fragment間傳值

*1.利用setArguments(bundle)方法

activity.xml中:

<Button 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="passValue"
    android:text="傳值"/>

<FrameLayout 
    android:id="@+id/fl_container"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:background="#999"
    android:layout_weight="1">
</FrameLayout>

content_fragment.xml中:

 <Button 
    android:id="@+id/btn_getValue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="取值"/>

<TextView 
    android:id="@+id/tv_value"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

MainActivity.java中:

public class MainActivity extends Activity {
    private FragmentManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        manager = getFragmentManager();
    }
    
    //當點選傳值按鈕時,Fragment才加入到Activity中,並傳值
    public void passValue(View view){
        FragmentTransaction transaction = manager.beginTransaction();
        ContentFragment fragment = new ContentFragment();   
        Bundle args = new Bundle();
        args.putString("key", "我是Activity傳遞的資訊");
        fragment.setArguments(args);//傳遞資料
        transaction.add(R.id.fl_container,fragment);
        transaction.commit();
    }
}

ContentFragment.java中:

public class ContentFragment extends Fragment {
    private Bundle arguments;
    private Button btnGetValue;
    private TextView tvValue;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_fragment, null);
        btnGetValue = (Button) view.findViewById(R.id.btn_getValue);
        tvValue = (TextView) view.findViewById(R.id.tv_value);
        
        arguments = getArguments();
        
        //在按鈕點選事件中取值
        btnGetValue.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if(arguments!=null){
                    String value = arguments.getString("key", "");
                    tvValue.setText("接收的資訊="+value);
                }               
            }
        });
        
        return view;
    }
}