Fragment Implementation
How fragment will inform the activity of any events?
We need to use the callback interface for fragment interaction through the activity. While coming to implementations, its nothing but the callback interface with a method.
interface CallbackInterface {
callbackMethod()
}
The activity is going to implement this particular interface as a part of it, it has to give the implementation of the callback method that is available in the callback interface
Activity implements CallbackInterface {
callbackMethod() - implementation
}
So who will invoke this particular method?
The fragments will be invoking this method. The fragments will have a instance of the CallbackInterface when the fragment is created.
How can we pass data from an Activity to Fragment?
In Activity, we need to do the following :
fragment.setArguement(Bundle)
In Fragment , we can get the data by calling :
Bundle = Fragment.getArguements()
public class MainActivity extends AppCompatActivity implements FragmentActionListener {
public String TAG = this.getClass().getSimpleName();
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
String selectedCountry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
if (findViewById(R.id.activity_main_portrait) != null) {
addCountriesFragment();
} else if (findViewById(R.id.activity_main_landscape) != null) {
addCountriesFragment();
addCountryDescriptionFragment(R.id.fragmentContainer2, savedInstanceState);
}
}
private void addCountriesFragment() {
fragmentTransaction = fragmentManager.beginTransaction();
CountriesFragment countriesFragment = new CountriesFragment();
countriesFragment.setFragmentActionListener(this);
fragmentTransaction.add(R.id.fragmentContainer, countriesFragment);
fragmentTransaction.commit();
}
private void addCountryDescriptionFragment(Bundle bundle) {
CountryDescriptionFragment countryDescriptionFragment = new CountryDescriptionFragment();
countryDescriptionFragment.setArguments(bundle);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, countryDescriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private void addCountryDescriptionFragment(int containerId, Bundle bundle) {
CountryDescriptionFragment countryDescriptionFragment = new CountryDescriptionFragment();
countryDescriptionFragment.setArguments(bundle);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(containerId, countryDescriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/*@Override
public void callBackMethod() {
Toast.makeText(this, "Trigger Other Fragment", Toast.LENGTH_SHORT).show();
addCountryDescriptionFragment();
}*/
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("selectedCountry", selectedCountry);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
selectedCountry = savedInstanceState.getString("selectedCountry", "India");
}
@Override
public void onActionPerformed(Bundle bundle) {
int actionPerformed = bundle.getInt(ACTION_KEY);
switch (actionPerformed) {
case ACTION_VALUE_COUNTRY_SELECTED:
selectedCountry = bundle.getString(FragmentActionListener.KEY_SELECTED_COUNTRY, "India");
if (findViewById(R.id.activity_main_landscape) == null) {
addCountryDescriptionFragment(bundle);
} else {
addCountryDescriptionFragment(R.id.fragmentContainer2, bundle);
}
break;
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
Bundle bundle = new Bundle();
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.i(TAG, "Landscape");
addCountriesFragment();
if (selectedCountry == null) {
bundle.putString(KEY_SELECTED_COUNTRY, "India");
addCountryDescriptionFragment(bundle);
} else {
bundle.putString(KEY_SELECTED_COUNTRY, selectedCountry);
addCountryDescriptionFragment(R.id.fragmentContainer2, bundle);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.i(TAG, "Portrait");
if (selectedCountry == null) {
addCountriesFragment();
} else {
bundle.putString(KEY_SELECTED_COUNTRY, selectedCountry);
addCountryDescriptionFragment(bundle);
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/silver"
android:id="@+id/activity_main_portrait"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragmentContainer"
android:layout_margin="5dp" />
</LinearLayout>
activity_main.xml-land
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/silver"
android:id="@+id/activity_main_landscape"
tools:context=".MainActivity">
<FrameLayout
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="@+id/fragmentContainer"
android:layout_margin="5dp" />
<FrameLayout
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_toEndOf="@+id/fragmentContainer"
android:layout_toRightOf="@+id/fragmentContainer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="@+id/fragmentContainer2"
android:layout_margin="5dp" />
</RelativeLayout>
public interface FragmentActionListener {
String ACTION_KEY = "action_key";
int ACTION_VALUE_COUNTRY_SELECTED = 1;
String KEY_SELECTED_COUNTRY="KEY_SELECTED_COUNTRY";
void onActionPerformed(Bundle bundle);
}
public class CountriesFragment extends Fragment {
View rootView;
Context context;
ListView lvCountries;
String[] countries;
ArrayAdapter<String> countriesAdapter;
CallbackInterface callbackInterface;
FragmentActionListener fragmentActionListener;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_countries, container, false);
initUI();
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null) {
fragmentActionListener = (MainActivity)getActivity();
}
}
@Override
public void onResume() {
super.onResume();
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Select a Country");
}
public void setCallbackInterface(CallbackInterface callbackInterface) {
this.callbackInterface = callbackInterface;
}
public void setFragmentActionListener(FragmentActionListener fragmentActionListener) {
this.fragmentActionListener = fragmentActionListener;
}
private void initUI() {
context = getContext();
countries = getResources().getStringArray(R.array.countries);
lvCountries = rootView.findViewById(R.id.listViewCountries);
countriesAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, countries);
lvCountries.setAdapter(countriesAdapter);
lvCountries.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(fragmentActionListener != null) {
Bundle bundle = new Bundle();
bundle.putInt(ACTION_KEY, ACTION_VALUE_COUNTRY_SELECTED);
bundle.putString(KEY_SELECTED_COUNTRY, countries[i]);
fragmentActionListener.onActionPerformed(bundle);
}
}
});
}
}
fragment_countries.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/light_blue">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listViewCountries">
</ListView>
</LinearLayout>
public class CountryDescriptionFragment extends Fragment {
private static final String COMMON_TAG = "CombinedLifeCycle";
private static final String FRAGMENT_NAME = CountryDescriptionFragment.class.getSimpleName();
private static final String TAG = COMMON_TAG;
View rootView;
TextView textViewCountryDescription;
String countryName;
String countryDescription;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_country_description,container,false);
initUI();
return rootView;
}
private void initUI(){
textViewCountryDescription = (TextView)rootView.findViewById(R.id.textViewCountryDescription);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null) {
countryName = savedInstanceState.getString(FragmentActionListener.KEY_SELECTED_COUNTRY,"India");
countryDescription = getString(getStringId(countryName));
} else {
Bundle bundle = getArguments();
countryName = bundle.getString(FragmentActionListener.KEY_SELECTED_COUNTRY,"India");
countryDescription = getString(getStringId(countryName));
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("selectedCountry", countryName);
}
@Override
public void onResume() {
super.onResume();
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(countryName);
textViewCountryDescription.setText(countryDescription);
}
private int getStringId(String countryName){
if(countryName.equals("India")){
return R.string.India;
}else if(countryName.equals("USA")){
return R.string.USA;
}else if(countryName.equals("Pakistan")){
return R.string.Pakistan;
}else if(countryName.equals("Bangladesh")){
return R.string.Bangladesh;
}else if(countryName.equals("Egypt")){
return R.string.Egypt;
}else if(countryName.equals("Indonesia")){
return R.string.Indonesia;
}else if(countryName.equals("UK")){
return R.string.UK;
}else if(countryName.equals("Germany")){
return R.string.Germany;
}else {
return R.string.India;
}
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
fragment_country_description.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/purple_700">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="@android:color/background_light"
android:id="@+id/textViewCountryDescription"/>
</LinearLayout>
strings.xml
<resources>
<string name="app_name">Frag_Impl_CodeTutor</string>
<string-array name="countries">
<item>India</item>
<item>USA</item>
<item>Pakistan</item>
<item>Bangladesh</item>
<item>Egypt</item>
<item>Indonesia</item>
<item>UK</item>
<item>Germany</item>
</string-array>
<string name="India">
India is a vast South Asian country with diverse terrain – from Himalayan peaks to Indian Ocean coastline – and history reaching back 5 millennia.
In the north, Mughal Empire landmarks include Delhi\’s Red Fort complex and massive Jama Masjid mosque, plus Agra’s iconic Taj Mahal mausoleum.
Pilgrims bathe in the Ganges in Varanasi, and Rishikesh is a yoga centre and base for Himalayan trekking.
</string>
<string name="USA">
The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest and Hawaii extending the nation\’s
presence into the Pacific Ocean. Major Atlantic Coast cities are New York, a global finance and culture center, and capital Washington, DC.
Midwestern metropolis Chicago is known for influential architecture and on the west coast, Los Angeles\' Hollywood is famed for filmmaking.
</string>
<string name="Pakistan">
Pakistan, officially the Islamic Republic of Pakistan, is a country in South Asia and on junction of West Asia, Central Asia and East Asia.
It is the fifth-most populous country with a population exceeding 209,970,000 people.
</string>
<string name="Bangladesh">
Bangladesh, to the east of India on the Bay of Bengal, is a South Asian country marked by lush greenery and many waterways.
Its Padma (Ganges), Meghna and Jamuna rivers create fertile plains, and travel by boat is common. On the southern coast, the Sundarbans,
an enormous mangrove forest shared with Eastern India, is home to the royal Bengal tiger.
</string>
<string name="Egypt">
Egypt, a country linking northeast Africa with the Middle East, dates to the time of the pharaohs. Millennia-old monuments sit along the
fertile Nile River Valley, including Giza\'s colossal Pyramids and Great Sphinx as well as Luxor\'s hieroglyph-lined Karnak Temple and
Valley of the Kings tombs. The capital, Cairo, is home to Ottoman landmarks like Muhammad Ali Mosque and the Egyptian Museum, a trove of antiquities.
</string>
<string name="Indonesia">
Indonesia, a Southeast Asian nation made up of thousands of volcanic islands, is home to hundreds of ethnic groups speaking many different languages.
It\’s known for beaches, volcanoes, Komodo dragons and jungles sheltering elephants, orangutans and tigers. On the island of Java lies Indonesia\'s
vibrant, sprawling capital, Jakarta, and the city of Yogyakarta, known for gamelan music and traditional puppetry.
</string>
<string name="UK">
The United Kingdom, made up of England, Scotland, Wales and Northern Ireland, is an island nation in northwestern Europe.
England – birthplace of Shakespeare and The Beatles – is home to the capital, London, a globally influential centre of finance and culture.
England is also site of Neolithic Stonehenge, Bath’s Roman spa and centuries-old universities at Oxford and Cambridge.
</string>
<string name="Germany">
Germany is a Western European country with a landscape of forests, rivers, mountain ranges and North Sea beaches.
It has over 2 millennia of history. Berlin, its capital, is home to art and nightlife scenes, the Brandenburg Gate and many sites relating to WWII.
Munich is known for its Oktoberfest and beer halls, including the 16th-century HofbrÀuhaus. Frankfurt, with its skyscrapers,
houses the European Central Bank.
</string>
</resources>
AndroidManifest,.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.keshav.frag_impl_codetutor">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Frag_Impl_CodeTutor">
<!--android:configChanges="keyboardHidden|orientation|screenSize"-->
<activity
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Comments
Post a Comment