gosulove gosulove - 4 months ago 23
Android Question

Android How to pass EditText and ImageView within Fragments

So what i want to do is that from first.java Fragment pass the EditText data and ImageView to two.java. I manage to replace first.java with two.java when i click the button (transaction.replace(R.id.top,Two);). I am familiar with Intent but i am not sure how to pass EditText and Imageview in Fragments. Please refer to the screenshot.

MainActivity.java

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
first first=new first();
transaction.add(R.id.top,first);
transaction.commit();
}
}


first.java

public class first extends Fragment implements View.OnClickListener{

Button get_button;
EditText get_input_name;
ImageView get_image;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_first,container,false);

get_input_name=(EditText)rootView.findViewById(R.id.input_name);
get_button=(Button)rootView.findViewById(R.id.submit);
get_image=(ImageView)rootView.findViewById(R.id.img1);
get_button.setOnClickListener(this);

return rootView;
}

public void onClick(View v){

FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two();
transaction.replace(R.id.top,Two);
transaction.commit();

}

}


two.java

public class two extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}

}


enter image description here

Anyone can help? thx

RRR RRR
Answer

Put both values in Bundle.

Bundle bundle = new Bundle();
bundle.putString("edtValue", <EditText value>);
bundle.putString("image", <Image path/url>);

Pass Bundle in Fragment

Two.setArguments(bundle);

Fetch these value in second fragment

Bundle bundle = getArguments();
String edtValue = bundle.getString("edtValue");

Tip : You should use camel case while declaring class name, check Java Coding Style Guidelines or Google Java Style Guide