Open a WebView in a fragment MainActivity - java

What I have: A navigation drawer, a fragment where I dispay rss news, two button on the bottom of the screen.
What I want: Open a webview inside the fragment by clicking one of the two button.
My files:
MainActivity.java:
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import com.jmsliu.rssreader.model.PostDataModel;
import com.jmsliu.rssreader.model.vo.DrawerData;
import com.jmsliu.rssreader.model.vo.PostData;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks,
PostListFragment.PostListFragmentInteractionListener{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
Button youTubeButton = (Button) findViewById(R.id.button2);
youTubeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
//PostListFragment postListFragment = (PostListFragment) getSupportFragmentManager().findFragmentById(R.id.postListView);
PostListFragment postListFragment = (PostListFragment) getSupportFragmentManager().findFragmentByTag("postlist_fragment");
DrawerData data = GlobalClass.instance().categoryList.get(position);
if(data.name != "") {
String url = String.format(GlobalClass.CATEGORY_RSSURL, data.name);
postListFragment.rssURL = String.format(GlobalClass.CATEGORY_RSSURL, data.name);
//Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
} else {
postListFragment.rssURL = GlobalClass.RSSURL;
//Toast.makeText(this, GlobalClass.instance().RSSURL, Toast.LENGTH_SHORT).show();
}
PostDataModel.getInstance().listData.clear();
PostDataModel.getInstance().guidList.clear();
postListFragment.manualRefresh();
}
#Override
public void onPostSelected(int index) {
PostData data = PostDataModel.getInstance().listData.get(index);
FragmentManager fragmentManager = getSupportFragmentManager();
PostViewFragment postViewFragment = (PostViewFragment) getSupportFragmentManager().findFragmentByTag("postview_fragment");
if(postViewFragment == null) {
postViewFragment = PostViewFragment.newInstance(data.postLink);
} else {
postViewFragment.urlLink = data.postLink;
}
postViewFragment.title = data.postTitle;
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, postViewFragment, "postview_fragment");
ft.addToBackStack(null);
ft.commit();
}
}
activity_main.xml:
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/postlist_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="postlist_fragment"
android:name="com.jmsliu.rssreader.PostListFragment"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SEGNALA"
android:id="#+id/segnala"
android:background="#000000"
android:textColor="#ffffff"
android:clickable="true"
android:layout_gravity="center|bottom"
android:layout_alignParentTop="false"
android:layout_alignWithParentIfMissing="false"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="false"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:text="YouTube"
android:background="#000000"
android:textColor="#ffffff"
android:clickable="true"
android:layout_gravity="right|bottom" />
</FrameLayout>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start" android:name="com.jmsliu.rssreader.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>

It looks simple. Just create new fragment with webview and make replace fragment inside button's on click listener like this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = WebViewFragment.newInstance(string dataOrAnythingYouWillUseToPassContent)
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, R.id.fragment_container,fragment).addToBackStack(stringTag).commit();
}
});
In webviewfragment static newInstance method pack data to fragments arguments, and retrieve it in onCreate method or whenever you will need them.

Related

Create NavigationDrawer in Fragment, NOT Activity

Would like to know how to create a NavigationDrawer within a Fragment (in this case my HomeFragment) and NOT in an Activity. Have seen everything on how to create a NavigationDrawer within an Activity, such as MainActivity, but my goal for this project is to create a NavigationDrawer ONLY for the HomeFragment. Don't want any of the other fragments to contain it. The drawer_menu will contain Edit Profile, Settings, and Log Out. Below I have posted what I have done... Is there a better way to do it? Code seems to be a bit awkward.
Every video I have seen, every post has been about creating a NavigationDrawer in Activities, so I'm wondering what the code would look like for Fragment. I tried doing it just like you would for Activity, but it wouldn't work.
Below you guys have my HomeFragment.java and fragment_home.xml
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".Fragment.HomeFragment"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_home_fragment"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?android:attr/windowBackground"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/events_logo_main_activity"
android:layout_width="180dp"
android:layout_height="45dp"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:src="#drawable/events_logo_black_max_size" />
<ImageView
android:id="#+id/camera_create_an_event_main_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="11dp"
android:src="#drawable/ic_camera_create_events_home_fragment_black" />
<ImageView
android:id="#+id/three_bars_settings_main_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerInParent="true"
android:src="#drawable/ic_three_bars_settings_home_fragment_black" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bar">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:itemTextColor="#color/colorPrimaryAqua50"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
HomeFragment.java
package com.e.events.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.e.events.Adapter.PostAdapter;
import com.e.events.EditProfileActivity;
import com.e.events.MainActivity;
import com.e.events.Model.Post;
import com.e.events.PostActivity;
import com.e.events.R;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
private ImageView options;
private DrawerLayout drawer;
ProgressBar progressBar;
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post> postLists;
private ImageView camera_create_event;
private List<String> followingList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists);
recyclerView.setAdapter(postAdapter);
progressBar = view.findViewById(R.id.progress_circular);
options = view.findViewById(R.id.three_bars_settings_main_activity);
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
Toolbar toolbar = view.findViewById(R.id.toolbar_home_fragment);
drawer = view.findViewById(R.id.drawer_layout);
camera_create_event = view.findViewById(R.id.camera_create_an_event_main_activity);
camera_create_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PostActivity.class);
startActivity(intent);
}
});
checkFollowing();
return view;
}
private void checkFollowing() {
followingList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followingList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
followingList.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readPosts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
for (String id : followingList) {
if (post.getPublisher().equals(id)) {
postLists.add(post);
}
}
}
postAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It's not possible.
Because To implement the Navigation Drawer we first need to add android.support.v4.widget.DrawerLayout as the root of the activity layout.
For Toggle Option of Navigation Drawer, We Require ToolBar.
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
The ToolBar is not possible in the fragment.
For Better use, Make Navigation View in Activity inside the DrawerLayout.

toolbar not showing in webview?

I am developing an android news app and implemented toolbar as a back arrow when the user clicks should go to the back
I am developing an android news app and implemented toolbar as a back arrow when the user clicks should go to the back
below my DetailActivity where I have implemented toolbar
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import edgar.yodgorbek.sportnews.R;
public class DetailActivity extends AppCompatActivity {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.imageView)
ImageView imageView;
#BindView(R.id.webView)
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
String imageUrl = getIntent().getExtras().getString("imageKey");
Picasso.get().load(imageUrl).into(imageView);
webView.getSettings().setJavaScriptEnabled(true);
String url = getIntent().getExtras().getString("urlKey");
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public class WebViewController extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
below my activity_detail.xml
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:layout_marginTop="32dp"
tools:ignore="ContentDescription" />
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView" />
</android.support.design.widget.CoordinatorLayout>

My app crashes on button click to start activity, but works in emulator

I have an android app which starts out at the main activity that contains a navigation view, and a fragment called fragment_home which has my start button. When I hit that button, another activity is started. This works fine in the device emulator, but it also works when I plug my phone in and build directly to it (Pixel 3XL with Android 9).
However, if I manually install the APK and run it with my phone unplugged, the main activity opens up fine and displays the home fragment contents, but when I press the button the app immediately crashes. Here is the code for my
MainActivity.java
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/*
* Avoid reloading fragment when device is rotated
*/
if(savedInstanceState == null)
{
getFragmentManager().beginTransaction().replace(R.id.placeholder_home, new HomeFragment()).commit();
navigationView.setCheckedItem(R.id.fragment_home);
}
}
/* Add functionality to the navigation drawer items */
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()) {
case R.id.home:
getFragmentManager().beginTransaction().replace(R.id.placeholder_home, new HomeFragment()).commit();
break;
case R.id.history:
getFragmentManager().beginTransaction().replace(R.id.placeholder_home, new HistoryFragment()).commit();
break;
case R.id.settings:
getFragmentManager().beginTransaction().replace(R.id.placeholder_home, new SettingsFragment()).commit();
break;
case R.id.help:
getFragmentManager().beginTransaction().replace(R.id.placeholder_home, new HelpFragment()).commit();
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
public void buttonClick(View v) {
switch(v.getId()) {
case R.id.startButton:
/* Start the survey activity */
Intent myIntent = new Intent(MainActivity.this, SurveyClass.class);
startActivity(myIntent);
break;
}
}
}
The buttonClick() function is the one that is run when the button from my home fragment is clicked.
Here is my home fragment XML code
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_home"
android:background="#color/colorPrimary">
<Button
android:id="#+id/startButton"
android:layout_width="256dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="120dp"
android:background="#drawable/button_rounded_corners_white"
android:fontFamily="#font/segoeuib"
android:gravity="center"
android:includeFontPadding="false"
android:onClick="buttonClick"
android:text="FIND PRODUCTS"
android:textColor="#color/colorAccent"
android:textSize="26sp" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="326dp"
android:layout_height="188dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="29dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="18dp"
app:srcCompat="#drawable/logo_white" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView2"
android:layout_centerHorizontal="true"
android:textColor="#color/white"
android:textSize="24dp"
android:textStyle="bold"
android:text="#string/subtitle" />
</RelativeLayout>
Do you work with android support v4 Fragment ?
If it's the case you need to use
getSupportFragmentManager().beginTransaction().replace(R.id.placeholder_home, new HomeFragment()).commit();
instead of
getFragmentManager().beginTransaction().replace(R.id.placeholder_home, new HomeFragment()).commit();
Can you also post the error obtained ?
This might be android 9 error!
Add this line in your Manifest file within application
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Implementing Swipe functionality on portion of screen while using bottom navigation?

I am developing my first Android application as part of a college project. I am relatively new to java. My application consists of a bottom navigation, which contains 4 separate pages. Within these pages I have a head section, containing a title, contact button and logout button.
Underneath the head section I wish to have a midsection which will in itself contain 3 swipe panels containing information. Essentially there should be 3 panels for each page, with there being 4 pages (So 4 sets of 3 swipe panels).
This is where I'm having difficulty.. I'm unsure of how to nest the fragments so that only that midsection will be swipe-able. Here is a screenshot of what I have so far:
Screenshot of app
Here is my Code for my MainActivity.java class:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
frag = MenuFragment.newInstance(getString(R.string.text_home),
getString(R.string.test_home));
break;
case R.id.menu_notifications:
//Call to a function that does the stuff here
frag = MenuFragment.newInstance(getString(R.string.text_notifications),
getString(R.string.test_notifications));
break;
case R.id.menu_search:
frag = MenuFragment.newInstance(getString(R.string.text_search),
getString(R.string.test_search));
break;
case R.id.menu_followed:
frag = MenuFragment.newInstance(getString(R.string.text_follow),
getString(R.string.test_follow));
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here is the acitivity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.socialivemusic.socialivetestproject.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ff292929">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="0.06"
android:background="#ff000000"
android:textAlignment="center"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
And here is my MenuFragment.java class:
import android.os.Bundle;
import android.support.annotation.Nullable;
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.TextView;
import org.w3c.dom.Text;
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private static final String ARG_TESTSTRING = "arg_testString";
private String mText;
private String mTest;
private View mContent;
private TextView mTextView;
private TextView mTestView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text, String testString) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putString(ARG_TESTSTRING, testString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve text and color from bundle or savedInstanceState
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
mTest = args.getString(ARG_TESTSTRING);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
mTest = savedInstanceState.getString(ARG_TESTSTRING);
}
// initialize views
mContent = view.findViewById(R.id.fragment_content);
mTextView = (TextView) view.findViewById(R.id.text);
mTestView = (TextView) view.findViewById(R.id.test);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text and background color
mTextView.setText(mText);
mTestView.setText(mTest);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
outState.putString(ARG_TESTSTRING, mTest);
super.onSaveInstanceState(outState);
}
}
Here is the fragments_menu.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.socialivemusic.socialivetestproject.MenuFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="150dp"
android:layout_marginTop="15dp"
android:background="#ff434343"
android:weightSum="1">
<Button
android:text="CONTACT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/contactButton"
android:layout_weight="0.33"
android:background="#drawable/round_button"
android:textSize="20sp"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#969696"
android:textSize="40sp"
android:textStyle="bold"
android:layout_weight="0.355"
/>
<Button
android:text="LOGOUT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/logoutbutton"
android:layout_weight="0.33"
android:background="#drawable/logout_button"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="185dp"
android:background="#ff434343">
<TextView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
The second LinearLayout in the above file is the one which should be the swipe-panel. The only other files on the project are xml files dealing with layout of the bottom navigation bar itself, so not relevant to the trouble I'm having.
Does anyone have any recommendations on how to approach this? A helping hand on how to start this part of the project would be amazing! Thanks in advance!

BottomBar fragments in Android studio

How can I add fragments for each tab in BottomBar in Android studio please a good example like list view or grid view for each tab..thanks
You need to implement SetOnTabSelectListerner.
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
Fragment fragment = null;
Class fragmentClass = null;
switch (tabId) {
case R.id.tab_one:
fragmentClass = TabOneFragment.class;
break;
case R.id.tab_two:
fragmentClass = TabTwoFragment.class;
break;
case R.id.tab_three:
fragmentClass = TabThreeFragment.class;
break;
case R.id.tab_four:
fragmentClass = TabFourFragment.class;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
});
main_activity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements communicator{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(int i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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="#00BBFF"
android:orientation="vertical"
tools:context="com.example.dhanya.myfragmentexample.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentexample.FragmentA"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentexample.FragmentB"
/>
</android.widget.LinearLayout>
fragmentA.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
list=(ListView)getActivity().findViewById(R.id.lv);
ArrayAdapter ad=ArrayAdapter.createFromResource(getActivity(),R.array.listval,android.R.layout.simple_list_item_1);
list.setAdapter(ad);
list.setOnItemClickListener(this);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt=(TextView)view;
String str=txt.getText().toString();
comm.respond(position);
}
}
fragmentA.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentexample.FragmentA"
android:background="#FFBB00">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv"/>
</FrameLayout>
fragmentB.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.textv);
}
public void changedata(int i)
{
Resources res=getResources();
String[] des=res.getStringArray(R.array.desciptions);
// String str=Integer.toString(i);
txt.setText(des[i]);
// txt.setText(str); }}
fragmentB.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentexample.FragmentB"
android:background="#99CC00"
>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textv"/>
</FrameLayout>
strings.xml
<resources>
<string name="app_name">MyFragmentExample</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
<string-array name="listval">
<item>fragments</item>
<item>Activities</item>
<item>Services</item>
<item>Content Providers</item>
</string-array>
<string-array name="desciptions">
<item>A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).</item>
<item>Activities are one of the fundamental building blocks of apps on the Android platform. They serve as the entry point for a user's interaction with an app, and are also central to how a user navigates within an app (as with the Back button) or between apps (as with the Recents button). </item>
<item>A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.</item>
<item>Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Implementing a content provider has many advantages. </item>
</string-array>
</resources>
communicator.java
public interface communicator {
public void respond(int i);
}
//Grid view
main_activity.xml
<ScrollView xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>
</ScrollView>
mainactivity.java
package com.example.harish.mylayoutexamples;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class GridActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
GridView gridView;
static final String[] numbers = new String[] {
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView) findViewById(R.id.gridview1);
// Create adapter to set value for grid view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
/* gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText() , Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText() , Toast.LENGTH_SHORT).show();
}
}
fragments dynamic loading
Main activity. Java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button firstFragment, secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);
// perform setOnClickListener event on First Button
firstFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load First Fragment
loadFragment(new FirstFragment());
}
});
// perform setOnClickListener event on Second Button
secondFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load Second Fragment
loadFragment(new SecondFragment());
}
});
}
private void loadFragment(Fragment fragment) {
// create a FragmentManager
FragmentManager fm = getFragmentManager();
// android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
//fragmentTransaction.add(R.id.firstFragment,fragment);
fragmentTransaction.commit(); // save the changes
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MAIN_ACTIVTY.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<!-- display two Button's and a FrameLayout to replace the Fragment's -->
<Button
android:id="#+id/firstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/button_background_color"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<Button
android:id="#+id/secondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/button_background_color"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
FIRST_FRAGMENT.JAVA
package com.abhiandroid.fragmentexample;
import android.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.Toast;
public class FirstFragment extends Fragment {
View view;
Button firstButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_first, container, false);
// get the reference of Button
firstButton = (Button) view.findViewById(R.id.firstButton);
// perform setOnClickListener on first Button
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
FIRST_FRAGMENT>XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.fragmentexample.FirstFragment">
<!--TextView and Button displayed in First Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is First Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/firstButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
SECOND_FRAGMENT>JAVA
package com.abhiandroid.fragmentexample;
import android.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.Toast;
public class SecondFragment extends Fragment {
View view;
Button secondButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_second, container, false);
// get the reference of Button
secondButton = (Button) view.findViewById(R.id.secondButton);
// perform setOnClickListener on second Button
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "Second Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
SECOND_FRAGMENT>XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.fragmentexample.SecondFragment">
<!--TextView and Button displayed in Second Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is Second Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/secondButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
main_activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(String i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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"
tools:context="com.example.dhanya.myfragmentcommsimple.MainActivity"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentA">
</fragment>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentB">
</fragment>
</android.widget.LinearLayout>
fragment_A.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.ListView;
public class FragmentA extends Fragment implements View.OnClickListener{
int count=0;
Button bt;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
bt=(Button)getActivity().findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
count++;
comm.respond("The button is clicked "+ count+" times");
}
}
FRAGMET_A.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentcommsimple.FragmentA"
android:background="#99FF00">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn"
android:text="counter"
android:layout_margin="40dp"/>
</FrameLayout>
FRAGMENT_B.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.tv);
}
public void changedata(String i)
{
txt.setText(i);
}
}
FRAGMENT_B.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentcommsimple.FragmentB"
android:background="#FFBB00">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="haiiii"
android:id="#+id/tv"
android:layout_margin="50dp"/>
</FrameLayout>
COMMUNICATOR.java
package com.example.dhanya.myfragmentcommsimple;
public interface communicator {
public void respond(String i);
}

Categories

Resources