I just started to learn the fragment API on Android.
I want just to send a message back to my containing activity(I did it). Now I want to clear a misunderstanding about downcasting.
Here is my fragment:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class DetailFragment extends Fragment {
private EditText textFirstName, textLastName, textAge;
private FragmentListener mListener;
public DetailFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (!(context instanceof FragmentListener)) throw new AssertionError();
mListener = (FragmentListener) context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
textFirstName = (EditText) rootView.findViewById(R.id.textFirstName);
textLastName = (EditText) rootView.findViewById(R.id.textLastName);
textAge = (EditText) rootView.findViewById(R.id.textAge);
Button doneButton = (Button) rootView.findViewById(R.id.done_button);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
done();
}
});
return rootView;
}
private void done() {
if (mListener == null) {
throw new AssertionError();
}
String firstName = textFirstName.getText().toString();
String lastName = textLastName.getText().toString();
int age = Integer.valueOf(textAge.getText().toString());
mListener.onFragmentFinish(firstName, lastName, age);
}
public interface FragmentListener {
void onFragmentFinish(String firstName, String lastName, int age);
}
}
I don't understand the downcasting here:
mListener = (FragmentListener) context;
How Context class relate to my FragmentListener interface?
I find this is contradictory to my knowledge about downcasting(Downcasting is casting to a subtype, downward to the inheritance tree.)
The two types, Context and FragmentListener are unrelated. However, a subclass of Context might implement the FragmentListener interface. Your onAttach() method checks that this is, in fact, what's happening and does the downcast so the FragmentListener functionality is available through the mListener member field.
Any Context (most likely an Activity) that attaches an instance of DetailFragment will need to implement DetailFragment.FragmentListener to avoid an AssertionError at run time.
Related
I am trying to implement fragments for a project in Android Studio. The point of the project is to select a color from a spinner in one fragment then pass it to the parent activity and then pass it from the parent activity to the second fragment to change the background color of the second fragment. The problem I am having is my listener in the palette activity is set to null despite the fact I invoke it in the onAttach function.
This is my code for the Fragment that causes the app to crash
package edu.temple.palettecolorapp;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link PaletteFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link PaletteFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PaletteFragment extends Fragment {
private String colorArr[];
private String translationArr[];
Context parent;
private final String mParam1 = "colors";
private final String mParam2 = "translation";
public OnFragmentInteractionListener mListener;
public PaletteFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*
* #return A new instance of fragment PaletteFragment.
*/
// TODO: Rename and change types and number of parameters
public static PaletteFragment newInstance(String colors[], String translation[]) {
PaletteFragment fragment = new PaletteFragment();
Bundle args = new Bundle();
args.putStringArray("colors", colors);
args.putStringArray("translation", translation);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.colorArr = getArguments().getStringArray(mParam1);
this.translationArr = getArguments().getStringArray(mParam2);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.parent = context;
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) parent;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
// this.parent = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_palette, container, false);
Spinner spinner = v.findViewById(R.id.spinner);
PaletteAdapter pa = new PaletteAdapter(parent,colorArr,translationArr);
spinner.setAdapter(pa);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = colorArr[position];
mListener.onColorSelection(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onColorSelection(String color);
}
}
This is in the main activity
package edu.temple.palettecolorapp;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
public class PaletteActivity extends AppCompatActivity implements PaletteFragment.OnFragmentInteractionListener {
PaletteFragment master;
ColorFragment subject;
FragmentTransaction ft;
private final String colors[] = {"blue", "green", "purple", "red", "gray", "cyan", "magenta", "yellow", "lime"};
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
Resources res = context.getResources();
String title = res.getString(R.string.palette_title);
setTitle(title);
setContentView(R.layout.activity_palette);
String translation[] = res.getStringArray(R.array.colors);
PaletteFragment master = PaletteFragment.newInstance(colors,translation);
ColorFragment subject = ColorFragment.newInstance("magenta");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment1,master);
ft.replace(R.id.fragment2,subject);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onColorSelection(String color) {
subject.updateBackgroundColor(color);
}
}
I am having trouble in this portion of the fragment in the 'onCreateView' method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_palette, container, false);
Spinner spinner = v.findViewById(R.id.spinner);
PaletteAdapter pa = new PaletteAdapter(parent,colorArr,translationArr);
spinner.setAdapter(pa);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = colorArr[position];
mListener.onColorSelection(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
The 'mListener.onColorSelection' call causes the error and this is what the output is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: edu.temple.palettecolorapp, PID: 14867
java.lang.NullPointerException: Attempt to invoke virtual method 'void edu.temple.palettecolorapp.ColorFragment.updateBackgroundColor(java.lang.String)' on a null object reference
at edu.temple.palettecolorapp.PaletteActivity.onColorSelection(PaletteActivity.java:45)
at edu.temple.palettecolorapp.PaletteFragment$1.onItemSelected(PaletteFragment.java:87)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
at android.widget.AdapterView.access$300(AdapterView.java:53)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Edit2: added ColorFragment 'updateBackgroundColor' method
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
* Use the {#link ColorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ColorFragment extends Fragment {
private View v;
TextView t;
String color;
private final String KEY = "color";
public ColorFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters
* #return A new instance of fragment ColorFragment.
*/
// TODO: Rename and change types and number of parameters
public static ColorFragment newInstance() {
ColorFragment fragment = new ColorFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.color = getArguments().getString(KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_color, container, false);
t = v.findViewById(R.id.textView);
t.setBackgroundColor(Color.BLACK);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void updateBackgroundColor(String c){ // causing problems
t.setBackgroundColor(Color.parseColor(c));
}
}
Apparently ColorFragment subject in PaletteActivity is null when calling #onColorSelection().
Please check the assignment of value for the variable and make sure it is not null.
#Override
public void onColorSelection(String color) {
subject.updateBackgroundColor(color);
}
EDIT:
change the line:
ColorFragment subject = ColorFragment.newInstance("magenta");
TO:
subject = ColorFragment.newInstance("magenta");
I'm facing some problems in Android development. Environment is set to run in min API 23.
This is what I try to achieve :
I have a MainActivity with a BottomNavigationView. When an item in the BottomNavigationView is clicked it launches a Fragment. This works very well,I can send data to a fragment and have an interface to dialog with my activity.
The problem is :
On my Last fragment (ProgramFragment), I would like to make a Form Wizard. So, I would like to launch other fragments from the ProgramFragment. I used the same method I used in the MainActivity and I can launch the first fragment (RecStartFragment) where there is a button in the Layout. I want that when the button is clicked, the next fragment (RecDataPatientFragment) is shown. I get an error when I click on the button, saying that :
java.lang.NullPointerException: Attempt to invoke interface method
'void x.RecStartFragment$OnRecStartFragmentListener.startRecProg()'
on a null object reference at
x.RecStartFragment$1.onClick(RecStartFragment.java:30)
Is there a way to achieve that ? Why is that working from an activity but not from a fragment ?
Here is the code of the fragment RecStartFragment
package x;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class RecStartFragment extends Fragment {
private static final String TAG = RecStartFragment.class.getName();
private View v;
OnRecStartFragmentListener onRecStartFragmentListener;
private Button btnStartRec;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if(v != null) {
return v;
}
v = inflater.inflate(R.layout.fragment_rec_start, null);
btnStartRec = v.findViewById(R.id.btn_start_rec);
btnStartRec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRecStartFragmentListener.startRecProg();
}
});
return v;
}
public interface OnRecStartFragmentListener
{
public void startRecProg();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
onRecStartFragmentListener = (OnRecStartFragmentListener) context;
} catch (Exception e)
{
}
}
Thank you in advance !
You have a Null Pointer Exception (NPE) indicating that the field OnRecStartFragmentListener onRecStartFragmentListener has not been initialised.
From your code, you are trying to initialise the field in onAttach() and catching exceptions, but not doing anything with them:
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
onRecStartFragmentListener = (OnRecStartFragmentListener) context;
} catch (Exception e)
{
}
}
Try printing the stacktrace of any exceptions:
e.printStackTrace()
The context passed in onAttach is your MainActivity ? If so, is it implementing OnRecStartFragmentListener ?
You should implement the interface in your activity:
Activity implementation:
public class MainActivity extends AppCompatActivity implements RecStartFragment.OnRecStartFragmentListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment();
}
#Override
public void startRecProg() {
//Do whatever you need do here.
Log.e("Calback:","Interface is working");
}
}
How to send data to another fragment in one activity?
I have two fragment that have been created using Android Studio Design View Editor. I ccreated these two fragment on my MainActivity. fragment1 is the ID of first fragment, it contain just EditText and a button. fragment2 is the ID of second fragment, it just contain textView.
How to send data from EditText of fragment1 to textView of fragment2?
I have write some code below, please check it.
MainActivity.java
package com.example.radioswiba.belajar2buahfragment;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements Fragment1.OnFragmentInteractionListener, Fragment2.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Fragment1.java
//this code was generated by Android Studio
//i have deleted some unused code and comments
package com.example.radioswiba.belajar2buahfragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class Fragment1 extends Fragment {
//let's define some of variable
private EditText text_input;
private Button button_send;
private OnFragmentInteractionListener mListener;
public Fragment1() {
// Required empty public constructor
}
//this generated by Android Studio
public static Fragment1 newInstance(String param1, String param2) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
//this generated by Android Studio
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// my code here
View rootView = inflater.inflate(R.layout.fragment_fragment1, container, false);
text_input = (EditText) rootView.findViewById(R.id.status_text);
button_send = (Button) rootView.findViewById(R.id.post_btn);
button_send.setOnClickListener(postStatus);
return rootView;
}
View.OnClickListener postStatus = new View.OnClickListener(){
#Override
public void onClick(View v){
text_of_me = text_input.getText().toString();
//
//WHAT SHOULD I WRITE HERE?
//SHOULD I USED BUNDLE?
}
};
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Fragment2.java
//the code almost same with Fragment1.java
I have search similar quenstion on stackoverflow, but i can not figure out. I have found many solution like below:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
There we create a new Fragment, meanwhile i have had two fragment on my activity, i have create it manually from file -> new -> new fragment from android Studio Menu. Should i create new Fragment by using above code?
A good way to communicate between fragments and/or activities is with Otto, an event bus library.
if you implement it correctly, I am quite confident it gonna solve your issue.
Here is few examples :
http://www.vogella.com/tutorials/JavaLibrary-EventBusOtto/article.html
https://github.com/CardinalNow/event-bus-example
http://www.recursiverobot.com/post/48752686831/playing-around-with-otto-on-android
I want to pass dogruYanlis value which is an integer array to these fragments. If I try to handle this with bundle it it sends anything. The array that I received in fragment class is always null. I think that I can't handle with bundle but I don't know how I can solve this problem...
The Activity that I want to send data
package oztiryaki.my;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class result extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Bundle bundle;
int[] dogruYanlis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
toolbar = (Toolbar) findViewById(R.id.toolbarResult);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Bundle list = getIntent().getExtras();
if(list == null){
return;
}
dogruYanlis = list.getIntArray("dogruYanlis");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
bundle = new Bundle();
bundle.putIntArray("dogruYanlis", dogruYanlis);
result2015Fragment f15 = new result2015Fragment();
f15.setArguments(bundle);
result2014Fragment f14 = new result2014Fragment();
f14.setArguments(bundle);
result2013Fragment f13 = new result2013Fragment();
f13.setArguments(bundle);
adapter.addFragment(f15, "2015");
adapter.addFragment(f14, "2014");
adapter.addFragment(f13, "2013");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
The one of fragment activity
package oztiryaki.my;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by oztir on 21.02.2016.
*/
public class result2015Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.result2015,container,false);
int[] dogruYanlis = getArguments().getIntArray("dogruYanlis");
if(dogruYanlis == null){
Toast.makeText(getActivity(),"null sory:(", Toast.LENGTH_LONG).show();
}
TextView ygs1hp = (TextView) v.findViewById(R.id.ygs1hp);
return v;
}
public void getArray(int[] dogruYanlis){
Toast.makeText(getActivity(),Integer.toString(dogruYanlis[0]), Toast.LENGTH_LONG).show();
}
}
I had a similar struggle, maybe this will help. In case if your variables in the activity are not changing after it is created, there is one simple way to reach out to the activity's variables from the fragment it creates:
get the context in the fragment
then you can get the value of the variable from the fragment
Context context;
public void onViewCreated(View v, Bundle savedInstanceState) {
context = getActivity();
int i = ((result)context).dogruYanlis[0];
}
Try to create a Fragment using the wizard that Android studio provides, which gives you a dummy Fragment, with all the Fragment methods you need to pass data and such:
package FRAGMENTS;
import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentLifecycleDemo extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String TEXT1 = "text1";
private static final String TEXT2 = "text2";
// the two strings are going to be used here
private TextView title;
private TextView subtitle;
private String text1;
private String text2;
private Context c;
private OnFragmentInteractionListener mListener;
public FragmentLifecycleDemo(Context c) {
// Required empty public constructor
this.c = c;
}
public static FragmentLifecycleDemo newInstance(String title, String subtitle, Context c) {
FragmentLifecycleDemo fragment = new FragmentLifecycleDemo(c);
Bundle args = new Bundle();
args.putString(TEXT1, title);
args.putString(TEXT2, subtitle);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(c, "Hi! onCreate has just been called.", Toast.LENGTH_SHORT).show();
if (getArguments() != null) {
text1 = getArguments().getString(TEXT1);
text2 = getArguments().getString(TEXT2);
}
}
private void init(View v) {
title = (TextView) v.findViewById(R.id.txtTry);
title.setText(text1);
subtitle = (TextView) v.findViewById(R.id.txtReal);
subtitle.setText(text2);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lifecycle_demo, container, false);
init(v);
Toast.makeText(c, "Greetings from onCreateView!", Toast.LENGTH_SHORT).show();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Toast.makeText(c, "Is it me, or a button has just been pressed?", Toast.LENGTH_SHORT).show();
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Toast.makeText(c, "Howdy! I've just been attached to the activity.", Toast.LENGTH_SHORT).show();
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
Toast.makeText(c, "Oh no! I've been detached u.u", Toast.LENGTH_SHORT).show();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
As you can see, the method where you should get the Bundle is the onCreate one, that receives the data you want to be available on the Fragment, which was send from the constructor named newInstance.
i have problem on my on Attach its doing red line on him and writing me :
"overrides deprecated method in 'android.support.v4.app.Fragment' "
Please help me understand what i am doing wrong ?
ty you for all the helpers !!
package com.example.omermalka.memecreator;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by omermalka on 14/11/2015.
*/
public class TopSectionFragment extends Fragment {
private static EditText TopText;
private static EditText BottomText;
TopSectionListener acitivtyCommander;
public interface TopSectionListener{
public void createMime(String top , String Bottom);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
acitivtyCommander = (TopSectionListener) activity;
}catch (ClassCastException e){
throw new ClassCastException(activity.toString());
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
TopText = (EditText) view.findViewById(R.id.TopTextInput);
BottomText = (EditText) view.findViewById(R.id.BottomTextInput);
final Button button = (Button) view.findViewById(R.id.BottomTextInput);
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View v) {
acitivtyCommander.createMime(TopText.getText().toString(),BottomText.getText().toString());
}
}
You need to change
public void onAttach(Activity activity)
to
public void onAttach(Context context)
Final code:
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
acitivtyCommander = (TopSectionListener) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}