I am creating a app in which i wanna slide images,so for that i will be using view pager.For the image i have created a fragment which will display the images.
Code
public class ImageSwitcher extends BaseFragment {
private ImageView imageView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
}
private void initialize() {
imageView = (ImageView) view.findViewById(R.id.image_switcher);
imageView.setBackgroundResource("");
}
Now at this line
imageView.setBackgroundResource("");
the image will come from the int array which i will pass.
My doubt is
How will i pass int values to fragments
Is there any better way to use image switcher
Pass your Integer value from your fragment using Bundle as below:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
Access the value in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int m_id=getArguments().getInt("id");
return inflater.inflate(R.layout.fragment, container, false);
}
class MyFragment extends Fragment {
private static final String ARG_BG_RES="ARG_BG_RES";
public Fragment() {}
static public newInstance(String backgroundRes) {
Bundle args = new Bundle();
args.putExtra(ARG_BG_RES, backgroundRes);
Fragment fragment = new Fragment();
fragment.setArguments(args);
return f;
void whereYouNeedIt() {
String backgroundRes = getArguments().getStringExtra(ARG_BG_RES);
...
}
}
From outside:
MyFragment f = MyFragment.newInstance("black");
Don't omit public Fragment() {} it's required by the OS.
You can use bundle to pass values to the fragment or during initializing pass values via a custom constructor
For background resource if you are not changing images based on some logic in code, apply it via XML background and a drawable :-/
Related
This is the activity class of my project
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_activity);
String LicID = "DATA"
Fragment FragmentDetail = new FragmentDetail();
Bundle data = new Bundle();
data.putString("data",LicID);
FragmentDetail.setArguments(data);
ViewPageAdapter adapter = new ViewPageAdapter(getSupportFragmentManager());
adapter.AddFragment(new FragmentDetail(),"Detail");
viewp.setAdapter(adapter);
tablay.setupWithViewPager(viewp);
}
}
This is my fragmentDetail activity. and it is a tab fragment...
public class FragmentDetail extends Fragment {
public FragmentDetail() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.detail_fragment,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String LicID = getArguments().getString ("data");
Toast.makeText(getContext(),""+LicID+" ",Toast.LENGTH_SHORT).show();
}
This code is not work.app crash without any error.... please help. thank you
in tab_activity:
public String LicID = "DATA"
When you want to access this variable from the fragment attached to activity,
in Detail Fragment :
((tab_activity) (getActivity)).LicID
so you don't have to pass arguments to the fragment and use bundle for this. If you need further assistance, please show your logcat
I think the problem is that you set argument to one fragment:
Fragment FragmentDetail = new FragmentDetail();
Bundle data = new Bundle();
data.putString("data",LicID);
FragmentDetail.setArguments(data);
And add to adapter another fragment:
adapter.AddFragment(new FragmentDetail(),"Detail");
Please, try to use the same fragment.
I want to know that is it a good practice to set the objects directly when creating a new Fragment like in the example below or should we always make our object Parcelable and pass through intent?
public class sample extends Fragment {
private Object obj1;
public static sample newInstance(Object obj) {
sample fragment = new sample();
fragment.setObj1(obj);
return fragment;
}
public void setObj1(Object obj1) {
this.obj1 = obj1;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
In either case, it will be helpful if someone could give me reasons why one is better than the other?
Yes you must use setArguments with a Bundle with all your Parcelables.
Thats because when recreated your Fragment will only have access to it getArguments() and all local variables will be null (or default for primitives).
The way to go is in your newInstance
public static sample newInstance(String obj) {
sample fragment = new sample();
Bundle args = new Bundle();
args.putString(STRING_PARAM_KEY, obj);
fragment.setArguments(args);
return fragment;
}
Then in your onCreateView
obj1 = getArguments().getString(STRING_PARAM_KEY);
Just declare in your class a constant for the key
static final String STRING_PARAM_KEY = "string_param_key";
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);
}
}
Anyone can help? thx
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
You cannot share data between two fragments if they are on different activities but you can declare a variable in activity and get the result in any of the two fragments.
If both fragment are on same activity you can use Bundle , putExtra method for sharing data.
Further read Link
RRR answer is right.
You can do this by using constructor too.
in second activity make on constructor with values you want to get.
String text;
String imagepath;
// or int imageid;
public Two(String text, String imagepath /* or int imageid*/) {
super();
this.text = text;
this.imagepath = imagepath;
//or
this.imageid = imageid;
}
and from first fragment do like this.
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two(get_input_name.getText().toString.Trim(),imagepath /*or R.drawable.Imageid*/);
transaction.replace(R.id.top,Two);
transaction.commit();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
Bundle args = new Bundle();
args.putInt("your_data",value);
two Two=new two();
two.setArguments(args);
transaction.replace(R.id.top,Two);
transaction.commit();
in two.java
Get these value and set in fragment
public class two extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Bundle b = getArguments();
String s = b.getInt("your_data");
// Do Whatever you want
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
i must pass two parameters from fragment to another fragment. First parameter is type String and second parameter is type int. i want pass parameters with bundle but doesn't work.
FIRST FRAGMENT
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("totale", totalAmount);
fragment.setArguments(bundle);
SECOND FRAGMENT
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
TextView titolo2 = (TextView) getView().findViewById(R.id.quantità 2);
Bundle bundle=this.getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(myInt);
return inflater.inflate(R.layout.fragment_two, container, false);
}
Change Second Fragment like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
TextView titolo2 = rootView.findViewById(R.id.quantità 2);
Bundle bundle=this.getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(myInt + "");
return rootView;
}
In first fragment write this:
TwoFragment fragment = new TwoFragment ();
Bundle bundle = new Bundle();
bundle.putInt("totale", totalAmount);
fragment.setArguments(bundle);
Second fragmnent:
Bundle bundle=getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(myInt);
Create a public class with two static members like this :
public class SomeClass {
public static String stringValue="";
public static int integerValue=0;
}
Then from your first fragment just set values like this :
SomeClass.stringValue="yourValue";
SomeClass.integerValue=yourIntegerValue;
You can use these variable from your second fragment where you want :
int a =SomeClass.integerValue;
String str=SomeClass.stringValue;
If both fragments belong to the same activity, better to use this approach:
In activity you should save references to fragments, and all comunications between this fragments should be through activity, let's name it BaseActivity. For example add to activity method which will pass params to second fragment:
void updateSecondFragment(int param1, String param2){
mFragment2.updateTitle(param2);
}
In second fragment:
void updateTitle(String title){
mTextView.setText(title);
}
And in first fragment:
BaseActivity mActivity;
#Override
void onAttach(Activity activity) {
if (activity instanceOf BaseActivity){
mActivity = (BaseActivity) activity;
}
}
private void updateSecondFragment(){
if (mActivity != null){
mActivity.updateSecondFragment(int param1, String param2);
}
}
You should do the work of second fragment as:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView titolo2 = view.findViewById(R.id.quantità 2);
Bundle bundle=getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(String.valueOf(myInt));
}
I don't understand how to transfer data between two fragments. I've tried this:
public class Connection extends Fragment
{
SendMessage sender;
public interface SendMessage
{
public void send(String one, String two);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//my data
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
send = (SendMessage) getActivity();
}
private class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(final Context context, Intent intent)
{
if(message.equals("POS"))
{
sender.send(position,id);
}
}
}
in the first fragment; in the MainActivity:
public class MainActivity extends FragmentActivity implements Connection.SendMessage
{
protected void onCreate(Bundle savedInstanceState)
{
//my code
}
#Override
public void send(String one, String two)
{
Map map = new Map();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
}
}
and in the Map fragment(it need to receive this data):
public class Map extends Fragment
{
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle bundle = new Bundle();
bundle.getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID");
}
//then show this on googleMaps
}
}
but I don't understand why this code doesn't work..could you help me? thanks...
1) Please change your class name from Map.java to anything else. Because in java map is imported as java.util Package.
2)
Fragment map = new Fragment ();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
map.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, map).commit();
and in recieve
Bundle bundle = getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID:"); (You miss : in ID)
}
Do This send fragment
String cid=id.getText().toString();
Fragment fr=new friendfragment();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("CID", cid);
fr.setArguments(args);
ft.commit();
Received fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("CID");
return inflater.inflate(R.layout.fragment, container, false);
}
Well, firstly. Your receiving fragment is actually accessing an empty bundle. You are doing this:
Bundle bundle = new Bundle();
bundle.getArguments();
Instead of:
Bundle bundle = getArguments();
Secondly, a good way to communicate between two fragments is by using an interface. The interface communicates with the activity and the activity with the second fragment.
Here's google's tutorial:
http://developer.android.com/training/basics/fragments/communicating.html
Also, it doesn't seem like you are inflating any xml layout file for your Map Fragment or even adding it with FragmentTransaction after you have created it. Here is a short and sweet tutorial for that as well:
http://android-er.blogspot.com/2011/12/programmatically-add-fragment.html