FragmentからFragmentへの値伝達(第3種)
2309 ワード
fragment 1もfragment 2もActivityにあるのでActivityによって中のコントロールを得ることができます
コード#コード#
Fragment1:
Fragment2:
コード#コード#
Fragment1:
package com.qianfeng.fragmenttofragment2;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
@SuppressLint("NewApi")
public class Fragment1 extends Fragment {
private Button btn1;
private EditText et1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_layout1, container,
false);
btn1 = (Button) view.findViewById(R.id.btn1);
et1 = (EditText) view.findViewById(R.id.et1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String strValues = et1.getText().toString().trim();
// fragment id Fragment getView() view
// findViewById()
// Fragment2 fragment2 = (Fragment2) getFragmentManager()
// .findFragmentById(R.id.fg2);
// TextView tv_show = (TextView) fragment2.getView().findViewById(
// R.id.tv_show);
// fragment1 fragment2 Activity Activity
TextView tv_show = (TextView) getActivity().findViewById(R.id.tv_show);
tv_show.setText(strValues);
}
});
return view;
}
}
Fragment2:
package com.qianfeng.fragmenttofragment2;
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 Fragment2 extends Fragment{
private TextView tv_show;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_layout2, container, false);
tv_show = (TextView) view.findViewById(R.id.tv_show);
return view;
}
}