I am trying to make an app with navigation drawer using fragment, where on the home screen there should be images and when you click the image it should take you to that particular image's fragment and video starts playing. But unfortunately I can't see any image on the home screen (maybe I am making mistake in layout). Please help me out. Thanks in advance.
Code below :-
main xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context="com.hangout.google.heedbasketball.MainActivity"
tools:openDrawer="start"
tools:deviceIds= "tv"
tools:ignore="MergeRootFrame">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimaryDark"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/i1"
android:src="#drawable/arena_reaction"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/i2"
android:src="#drawable/frequentflyer_diop"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/i3"
android:src="#drawable/frequentflyer_tyus"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragement_container" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
main java file
package com.hangout.google.heedbasketball;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
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.support.v7.widget.Toolbar;
import android.view.MenuItem;
abstract class MainActivity4 extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this );
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle
(this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_sound:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new SoundFragment()).commit();
break;
case R.id.nav_notifications:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new NotificationsFragment()).commit();
break;
case R.id.nav_sponsors:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new SponsorsFragment()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new AboutFragment()).commit();
break;
case R.id.nav_contact_us:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new ContactusFragment()).commit();
break;
case R.id.nav_privacy:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new PrivacyFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new FirstFragment()).commit();
fragment = new FirstFragment();
break;
case 1:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new SecondFragment()).commit();
fragment = new SecondFragment();
case 2:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new ThirdFragment()).commit();
fragment = new ThirdFragment();
break;
default:
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
public void onBackpressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
onBackPressed();
}
}
}
Here is the java fragment for one video I have defined in the same way for other videos too
package com.hangout.google.heedbasketball;
import android.content.Context;
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.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link FirstFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link FirstFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FirstFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FirstFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FirstFragment.
*/
// TODO: Rename and change types and number of parameters
public static FirstFragment newInstance(String param1, String param2) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
//My video code here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
VideoView v1 = (VideoView) findViewById(R.id.v1);
v1.setVideoURI(Uri.parse("https://myvideo.mp4"));
v1.start();
v1.requestFocus();
v1.setKeepScreenOn(true);
}
}
private Object findViewById(int v1) {
return 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
// 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;
}
/**
* 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);
}
}
xml file fragment for the video
<?xml version="1.0" encoding="utf-8"?>
<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=".FirstFragment"
android:background="#color/colorPrimaryDark">
<!-- TODO: Update blank fragment layout -->
<VideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/v1" />
</RelativeLayout>
You have created findViewById function in on create which returns 0.
You need a video reference from layout which you are inflating.
Something similar to this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
// see the difference
VideoView v1 = (VideoView) view.findViewById(R.id.v1);
v1.setVideoURI(Uri.parse("https://myvideo.mp4"));
v1.start();
v1.requestFocus();
v1.setKeepScreenOn(true);
return view;
}
Related
I am very new to java and android development. So, even after reading many tutorials(e.g. this, this), I can't figure out how to call a fragment from a bottomnevigationmenu item.
Currently, I have:
MainActivity.java
package com.example.myapplication;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private void loadCalFragment() {
String string1="Hello",string2 = "Hii";
CalFragment fragment = CalFragment.newInstance(string1,string2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Context context = getApplicationContext();
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
Toast toasth = Toast.makeText(context , R.string.title_home, Toast.LENGTH_LONG);
toasth.show();
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
loadCalFragment();
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_location);
Toast toastn = Toast.makeText(context , R.string.title_location, Toast.LENGTH_LONG);
toastn.show();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
activaty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity">
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:text="#string/title_home"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Now, when I am adding a fragment using android-studio, it has created the xml file. My target is to create a datepicker in this fragment and show it. But, I don't know how to do that.
fragment_cal.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.myapplication.CalFragment">
<!-- TODO: Update blank fragment layout -->
<DatePicker
android:id="#+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
</FrameLayout>
and a corresponding java file:
calFragment.java
package com.example.myapplication;
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;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CalFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CalFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CalFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CalFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CalFragment.
*/
// TODO: Rename and change types and number of parameters
public static CalFragment newInstance(String param1, String param2) {
CalFragment fragment = new CalFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#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
return inflater.inflate(R.layout.fragment_cal, container, false);
}
// 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;
}
/**
* 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);
}
}
My AndroidManifest.xml is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<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/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
When I am trying to attach the CalFragment() call to the nevigation menu as:
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
CalFragment();
return true;
its giving error: Error:(32, 21) error: cannot find symbol method CalFragment()
I will be grateful if somebody kindly help me in it.
You are using same name for fragment CalFragment() and method CalFragment()
change to below:
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
loadCalFragment();
return true;
When your are calling fragment, create loadCalFragment(); method
Create method like below in your Activity class , you are not passing two string values to your fragment newInstance pass using CalFragment fragment = CalFragment.newInstance(string1,string2); pass your actual data here i used demo data:
private void loadCalFragment() {
String string1,string2 = "Hii"
CalFragment fragment = CalFragment.newInstance(string1,string2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
Update your code from my Code (Activity):
package com.example.myapplication;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Context context = getApplicationContext();
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
Toast toasth = Toast.makeText(context , R.string.title_home, Toast.LENGTH_LONG);
toasth.show();
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
loadCalFragment();
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_location);
Toast toastn = Toast.makeText(context , R.string.title_location, Toast.LENGTH_LONG);
toastn.show();
return true;
}
return false;
}
};
private void loadCalFragment() {
CalFragment fragment = CalFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
}
And CalFragment Code Here :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CalFragment extends Fragment {
public CalFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cal, container, false);
}
}
Here is the full answer.
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/app_tab_bar">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
app_tab_bar.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:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/activity_main" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:itemBackground="#android:color/white"
android:foreground="?attr/selectableItemBackground"
app:itemIconTint="#color/colorAccent"
app:itemTextColor="#color/colorAccent"
app:menu="#menu/navigation" />
</android.support.design.widget.CoordinatorLayout>
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// load the first fragment by default
loadFragment(new Frag_one());
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_explore:
fragment = new Frag_one();
loadFragment(fragment);
return true;
case R.id.navigation_saved:
fragment = new Frag_two();
loadFragment(fragment);
return true;
case R.id.navigation_inbox:
fragment = new Frag_three();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
fragment = new Frag_four();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
In order to display a fragment you have to define a container in xml file.
Framelayout serves as placeholder for your fragments. So in your mainactivity.xml you need to define the container as I did in my code.
i want to disable the swipe function in the tabbed activity. I tried some examples i found but it didn't worked or the code was completely different.
Here is my code:
MainActivity.java:
package com.example;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return FragmentOne.newInstance("a","b");
case 1:
return FragmentTwo.newInstance("a","b");
case 2:
return FragmentThree.newInstance("a","b");
case 3:
return FragmentFour.newInstance("a","b");
case 4:
return FragmentFive.newInstance("a","b");
default:
return FragmentThree.newInstance("a","b");
}
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "One";
case 1:
return "Two";
case 2:
return "Three";
case 3:
return "Four";
case 4:
return "Five";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.MainActivity"
android:background="#1d2935">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/fab_margin"
android:src="#mipmap/icon_plus_normal"
app:backgroundTint="#1d2935" />
</android.support.design.widget.CoordinatorLayout>
You need to create Custom ViewPager Class this way .
public class CustomViewPager extends ViewPager {
private boolean swipeable = false;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
// Call this method in your motion events when you want to disable or enable
// It should work as desired.
public void setSwipeable(boolean swipeable) {
this.swipeable = swipeable;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
return (this.swipeable) ? super.onInterceptTouchEvent(arg0) : false;
}
Now
CustomViewPager ViewPagerObj = (CustomViewPager)findViewById(R.id.container);
ViewPagerObj.setSwipeable(false);
You should add this in your XML
<Your_packagename.CustomViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
The accepted answer does not work for me. Beginners can just use this kotlin file instead of the accepted answer java file.
class CustomViewPager: ViewPager {
private var swipeable = false
constructor(context: Context) : super(context)
constructor(context:Context, attrs: AttributeSet) : super(context, attrs)
fun setSwipeable(swipeable:Boolean) {
this.swipeable = swipeable
}
override fun onInterceptTouchEvent(arg0: MotionEvent):Boolean {
return if ((this.swipeable)) super.onInterceptTouchEvent(arg0) else false
}
override fun onTouchEvent(event:MotionEvent):Boolean {
return if (this.swipeable) super.onTouchEvent(event) else false
}
}
The setup I have is a main_activity fragment that just has welcome text, and when you tap the start button, it's supposed to switch fragments. Instead of replacing the current fragment, it just overlays it on top of the main_activity fragment and won't allow me to perform the action associated with the new fragment.
Main Activity example
quote_fragment overlapping main activity
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:contextClickable="false"
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="me.alexoladele.quotebook.MainActivity">
<TextView
android:id="#+id/welcome_screen_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="144dp"
android:gravity="center"
android:text="#string/welcome_screen_text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="36sp" />
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="47dp"
android:clickable="true"
android:enabled="true"
android:text="#string/start_button" />
</FrameLayout>
ActivityMain.java
package me.alexoladele.quotebook;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int count = 0;
final QuoteFragment quoteFragment = new QuoteFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button startButton = (Button) findViewById(R.id.start_button);
final TextView welcomeText = (TextView) findViewById(R.id.welcome_screen_text);
if (startButton != null)
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSecondFragment(); // start your fragment from MainActivity
//startButton.setVisibility(v.GONE);
//welcomeText.setVisibility(v.GONE);
}
});
}
// This method will be in charge of handling your second fragment
private void startSecondFragment() {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.main_activity, quoteFragment)
.commit();
}
}
quote_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/quote_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:contextClickable="true">
<TextView
android:id="#+id/quote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="#string/tap_screen"
android:textColor="#a6a6a6"
android:textSize="26sp" />
<TextView
android:id="#+id/person"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="#string/quotist_name"
android:textColor="#585858"
android:textSize="26sp"
android:visibility="visible" />
</FrameLayout>
QuoteFragment.java:
package me.alexoladele.quotebook;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//import android.support.v4.app.Fragment;
public class QuoteFragment extends android.support.v4.app.Fragment {
int count = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.quote_fragment,container, false);
FrameLayout touch = (FrameLayout) v.findViewById(R.id.main_activity);
final TextView quoteText = (TextView) v.findViewById(R.id.quote);
// Makes quotes array
//region Description
String[] quotes = {
(Quotes go here, but I didn't put them here to save space)
};
//endregion
// Put quotes array into arraylist
final List<String> quoteList = new ArrayList<>(Arrays.asList(quotes));
//
if (touch != null)
touch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (count >= quoteList.size()) {
count = 0;
}
Quote q = new Quote("");
q.setQuote(quoteList.get(count));
quoteText.setText(q.getQuote());
count++;
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.quote_fragment, container, false);
}
}
welcome_screen_fragment:
<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"
android:clickable="true"
tools:context="me.alexoladele.quotebook.WelcomeScreen">
<TextView
android:id="#+id/welcome_screen_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="144dp"
android:gravity="center"
android:text="#string/welcome_screen_text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="36sp" />
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="47dp"
android:clickable="true"
android:enabled="true"
android:text="#string/start_button" />
</FrameLayout>
WelcomeScreen.java:
package me.alexoladele.quotebook;
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;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link WelcomeScreen.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link WelcomeScreen#newInstance} factory method to
* create an instance of this fragment.
*/
public class WelcomeScreen extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
//private OnFragmentInteractionListener mListener;
public WelcomeScreen() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment WelcomeScreen.
*/
// TODO: Rename and change types and number of parameters
public static WelcomeScreen newInstance(String param1, String param2) {
WelcomeScreen fragment = new WelcomeScreen();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#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
return inflater.inflate(R.layout.welcome_screen_fragment, container, false);
}
/* // 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;
}
*//**
* 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);
}*/
}
Don't replace your top-level view group. Create an empty frame layout inside of the top-level frame layout and use that as the ID to replace.
If you have elements in the main layout you no longer want visible you'll have to hide them (or use a fragment to show them in the first place which will get replaced).
UPDATE:
Still having the same problem, but I've added a fragment into the main_activity
welcome_screen_fragment:
<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"
android:clickable="true"
tools:context="me.alexoladele.quotebook.WelcomeScreen">
<TextView
android:id="#+id/welcome_screen_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="144dp"
android:gravity="center"
android:text="#string/welcome_screen_text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="36sp" />
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="47dp"
android:clickable="true"
android:enabled="true"
android:text="#string/start_button" />
</FrameLayout>
WelcomeScreen.java:
package me.alexoladele.quotebook;
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;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link WelcomeScreen.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link WelcomeScreen#newInstance} factory method to
* create an instance of this fragment.
*/
public class WelcomeScreen extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
//private OnFragmentInteractionListener mListener;
public WelcomeScreen() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment WelcomeScreen.
*/
// TODO: Rename and change types and number of parameters
public static WelcomeScreen newInstance(String param1, String param2) {
WelcomeScreen fragment = new WelcomeScreen();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#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
return inflater.inflate(R.layout.welcome_screen_fragment, container, false);
}
/* // 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;
}
*//**
* 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);
}*/
}
ORIGINAL:
The setup I have is a main_activity fragment that just has welcome text, and when you tap the start button, it's supposed to switch fragments. Instead of replacing the current fragment, it just overlays it on top of the main_activity fragment and won't allow me to perform the action associated with the new fragment.
Main Activity example
quote_fragment overlapping main activity
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:contextClickable="false"
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="me.alexoladele.quotebook.MainActivity">
<TextView
android:id="#+id/welcome_screen_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="144dp"
android:gravity="center"
android:text="#string/welcome_screen_text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="36sp" />
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="47dp"
android:clickable="true"
android:enabled="true"
android:text="#string/start_button" />
</FrameLayout>
ActivityMain.java
package me.alexoladele.quotebook;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int count = 0;
final QuoteFragment quoteFragment = new QuoteFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button startButton = (Button) findViewById(R.id.start_button);
final TextView welcomeText = (TextView) findViewById(R.id.welcome_screen_text);
if (startButton != null)
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSecondFragment(); // start your fragment from MainActivity
//startButton.setVisibility(v.GONE);
//welcomeText.setVisibility(v.GONE);
}
});
}
// This method will be in charge of handling your second fragment
private void startSecondFragment() {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.main_activity, quoteFragment)
.commit();
}
}
quote_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/quote_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:contextClickable="true">
<TextView
android:id="#+id/quote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="#string/tap_screen"
android:textColor="#a6a6a6"
android:textSize="26sp" />
<TextView
android:id="#+id/person"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="#string/quotist_name"
android:textColor="#585858"
android:textSize="26sp"
android:visibility="visible" />
</FrameLayout>
QuoteFragment.java:
package me.alexoladele.quotebook;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//import android.support.v4.app.Fragment;
public class QuoteFragment extends android.support.v4.app.Fragment {
int count = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.quote_fragment,container, false);
FrameLayout touch = (FrameLayout) v.findViewById(R.id.main_activity);
final TextView quoteText = (TextView) v.findViewById(R.id.quote);
// Makes quotes array
//region Description
String[] quotes = {
(Quotes go here, but I didnt put them here to save space)
};
//endregion
// Put quotes array into arraylist
final List<String> quoteList = new ArrayList<>(Arrays.asList(quotes));
//
if (touch != null)
touch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (count >= quoteList.size()) {
count = 0;
}
Quote q = new Quote("");
q.setQuote(quoteList.get(count));
quoteText.setText(q.getQuote());
count++;
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.quote_fragment, container, false);
}
}
I am new to android programming and I am trying to write a simple application that switches between two Fragments. I started a new project with a blank activity template that already included a Fragment. I think this could be where I am going wrong, but I am lost. Every time I launch and click the button the app crashes. It throws a must implement OnFragmentInteractionListener error from MyFragment2's onAttach method. If I comment that method out it add's the new Fragment on top of the old one. I have been through just about every tutorial I can find. I do not see where my code is going wrong. I'm sure it is something easy and I am going to feel pretty stupid when I finally figure it out. Any help would be appreciated. Thanks in advance.
My main activity:
package com.example.misanthropic.fragments;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// matically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void buttonClicked(View v){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment2 myFragment = new Fragment2();
fragmentTransaction.replace(R.id.fragment_main, myFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
The MyFragment2 I would like to swap in:
package com.example.misanthropic.fragments;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Fragment2.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Fragment2#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class Fragment2 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Fragment2.
*/
// TODO: Rename and change types and number of parameters
public static Fragment2 newInstance(String param1, String param2) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}
// 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(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#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 onFragmentInteraction(Uri uri);
}
}
My main xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main"
tools:ignore="MergeRootFrame" />
My Initial 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Main$PlaceholderFragment"
android:id="#+id/fragment_main">
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="165dp"
android:onClick="buttonClicked" />
</RelativeLayout>
The replacement Fragment 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.misanthropic.fragments.Fragment2">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
Figured it out. I was calling the wrong id in the replace method.
fragmentTransaction.replace(R.id.fragment_main, myFragment);
should have been:
fragmentTransaction.replace(R.id.container, myFragment);