How to navigate from one Fragment to another? - java

Here is my code:
activity_main.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: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" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/viewOneText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="182dp"
android:text="First View"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/viewOneBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/viewOneText"
android:layout_below="#+id/viewOneText"
android:layout_marginTop="17dp"
android:text="Click Here" />
<include layout = "#layout/drop_down"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="174dp"
android:text="Custom Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
MainActivity.java
package com.example.fragmenttest;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private ViewPager viewPager;
private MyAdapter pageAdapter;
private static final int ITEMS = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
pageAdapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(pageAdapter);
}
#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;
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
if(position==0)
{
return new FirstView();
}
else
{
return new SecondView();
}
}
}
public void setCurrentItem (int item, boolean smoothScroll) {
viewPager.setCurrentItem(item, smoothScroll);
}
public void onMenuItemClicked(View view) {
Toast.makeText(this, "LOL", Toast.LENGTH_LONG).show();
}
}
FirstView.java
package com.example.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstView extends DropDownMenu
{
private TextView firstText;
private Button btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view1,container,false);
firstText = (TextView)view.findViewById(R.id.viewOneText);
btn = (Button)view.findViewById(R.id.viewOneBtn);
btn.setOnClickListener(new ButtonEvent());
return view;
}
private class ButtonEvent implements OnClickListener
{
}
}
CustomView.java
package com.example.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class CustomView extends Fragment
{
private TextView secondText;
private Button secondViewBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.custom_view,container,false);
return view;
}
}
When I click the button in fragment_view1.xml, I need to go to custom_view.xml screen. It is a totally different fragment. How can I do this?

Add this to your OnClickListener:
CustomView cv = new CustomView();
FragmentManager fm= getFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
ft.replace(R.id.custom_view, cv);
ft.commit();
You need to add this to the RelativeLayout in your
custom_view.xml
android:id="#+id/custom_view"

Try this...place inside listener
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

//Create one FrameLayout and give the id as fragment_view in your fragment_view1.xml
and do like below
add this line in your layout fragment_view1.xml
<FrameLayout
android:id="#+id/fragment_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
private class ButtonEvent implements OnClickListener
{
CustomView custFra = new CustomView();
fragmentTransaction.replace(R.id.fragment_view, custFra).commit();
}

Related

How to change multiple fragments by clicking on a single button in android?

Greeting!
I’m practicing on fragments topic. My main issue is how to change multiple fragments by clicking a single button “NEXT” or “PREVIOUS” as you may know some apps or books change pages by clicking on the next or previous buttons. If there are only two are four fragments then no issue to add buttons but what if there are multiple fragments like 50 or 100? First I try to find solutions from Google and YouTube but I find that we can change pictures through this method. Is it possible that we can change fragments through this method or not if possible so please some articles with the same solutions to share your experience? Or I should need to use images to do this. My main activity java code and XML code are below and the first fragment and code other three fragments are also the same.
// Main_Activity.java
package com.test.fragment_practice;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.test.fragment_practice.Fragments.FirstFragment;
import com.test.fragment_practice.Fragments.ForthFragment;
import com.test.fragment_practice.Fragments.SecondFragment;
import com.test.fragment_practice.Fragments.ThirdFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
LinearLayout layout;
Button btn1,btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.linearLayout2);
btn1 = (Button) findViewById(R.id.btnpre);
btn2 = (Button) findViewById(R.id.btnnxt);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirstFragment fragment = new FirstFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.linearLayout2, fragment);
fragmentTransaction.commit();
}
});
btn2.setOnClickListener((view) ->{
SecondFragment fragment2 = new SecondFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.linearLayout2, fragment2);
fragmentTransaction.commit();
});
}
}
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF3700B3"
android:orientation="horizontal">
<Button
android:id="#+id/btnpre"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:backgroundTint="#FF0000"
android:text="Previous"
android:textColor="#6900FF"
android:textSize="24sp" />
<Button
android:id="#+id/btnnxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:backgroundTint="#FFFF00"
android:text="Next"
android:textColor="#6900FF"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
</LinearLayout>
// First_Fragment.java
package com.test.fragment_practice.Fragments;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.test.fragment_practice.R;
import com.test.fragment_practice.SecondActivity;
public class FirstFragment extends Fragment {
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_first, container, false);
}
}

Switching between fragments in a layout with BottomNavigationView

This is my first attempt to develop an android application.
I have a MainActivity with ConstraintLayout that has BottomNavigationView. Whenever the first navigation item is selected, I want to display a list of category (displayed in a fragment), then whenever this category is selected, another list will be displayed for items related to that particular category (in another fragment).
I have read in (Android - fragment .replace() doesn't replace content - puts it on top) it states that "static fragments written in XML are unable to be replaced, it has to be in a fragment container", how does it look like?
I tried to create my fragment container, but there is something wrong when I try to get the ListView (grand child of the container)
categoriesListView = getView().findViewById(R.id.categoriesList);
returns null.
MainActivity
package com.alsowaygh.getitdone.view.main;
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.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.services.CategoriesListFragment;
import com.alsowaygh.getitdone.view.services.OnCategorySelectedListener;
import com.alsowaygh.getitdone.view.services.ServicesListFragment;
public class MainActivity extends AppCompatActivity implements OnCategorySelectedListener {
private static final String TAG = "MainActivity";
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.add(R.id.container, categoriesListFragment);
fragmentTransaction.commit();
return true;
case R.id.navigation_bookings:
// mTextMessage.setText(R.string.title_bookings);
return true;
case R.id.navigation_chats:
// mTextMessage.setText(R.string.title_chats);
return true;
case R.id.navigation_settings:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
}
#Override
public void onCategorySelected(String category) {
Log.w(TAG, "Successfully created CategoryListFragment!");
}
}
activity_main layout
<?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=".view.main.MainActivity">
<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>
Fragment
package com.alsowaygh.getitdone.view.services;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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 com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.main.MainActivity;
public class CategoriesListFragment extends Fragment {
private ListView categoriesListView;
OnCategorySelectedListener categoryListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
//initializing root view first to refer to it
View rootView = inflater.inflate(R.layout.activity_main, container, false);
//initializing ListView
categoriesListView = getView().findViewById(R.id.categoriesList);
//categories list
final String[] categories = {"first category", "second category", "third category", "Fourth category"};
//initializing and adding categories strings to the addapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this.getContext(),
R.layout.category_textview);
for (String c : categories) {
arrayAdapter.add(c);
}
categoriesListView.setAdapter(arrayAdapter);
//implement onListItemClick
categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//retrieve string from categories list at clicked position
categoryListener.onCategorySelected(categories[position]);
}
});
return rootView;
}
#Override //to fource container activity to implement the OnCategorySelectedListener
public void onAttach(Context context) {
super.onAttach(context);
try{
categoryListener = (OnCategorySelectedListener) context;
}catch(ClassCastException e){
throw new ClassCastException(context.toString() + "must implement OnCategorySelectedListener");
}
}
}
fragments container
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</fragment>
</FrameLayout>
Your help will be much appreciated.
You need to add the FrameLayout container within the layout file of the MainActivity(activity_main), onclick of the buttons in BottomNavigationView replace with the fragment. In this way you have a Activity and the fragments are shown within the activity, on click of each menu item you can invoke to replace it with the fragments.
This should resolve your problem.
You need to change the layout as below in activity_main.xml.
<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=".view.main.MainActivity">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
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>
In the MainActivity code, you need to change as below:
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.replace(R.id.frame, categoriesListFragment);
fragmentTransaction.commit();
return true;
In the fragment layout file change to LinearLayout:
<LinearLayout
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</LinearLayout>
EDIT
In the fragment code, change the layout to the name of the fragment layout file(R.layout.fragment_layout_name).
View rootView = inflater.inflate(R.layout.fragment_layout_name, container, false);
//initializing ListView
categoriesListView = rootView.findViewById(R.id.categoriesList);

Tabs in a Fragment dont show up

I have read many questions here about tabs in a fragment, and did everything described here: https://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html
i got no error and the app doesn't crash or something, but the fragment is just empty. The JobFragment class is a simple fragment with just one label, but it isn't displayed.
here is my java code:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AutoFragment extends Fragment{
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_auto);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
JobFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
JobFragment.class, null);
return mTabHost;
}
#Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
}
and here is my layout xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Try changing this line to:
mTabHost.setup(getActivity(), getSupportFragmentManager(), R.layout.fragment_auto);

Unable to replace/navigate fragments

I am trying to navigate from one fragment to another. These two fragments are 100% different, there is no ViewPager or something like that to connect them. Here is the code.
fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/firstView">
<TextView
android:id="#+id/viewOneText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="182dp"
android:text="First View"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/viewOneBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/viewOneText"
android:layout_below="#+id/viewOneText"
android:layout_marginTop="17dp"
android:text="Click Here" />
<include layout = "#layout/drop_down"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_alignParentBottom="true"/>
<FrameLayout
android:id="#+id/fragment_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/customFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="174dp"
android:text="Custom Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
FirstView.java (uses fragment_view1.xml)
package com.example.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstView extends DropDownMenu
{
private TextView firstText;
private Button btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view1,container,false);
firstText = (TextView)view.findViewById(R.id.viewOneText);
btn = (Button)view.findViewById(R.id.viewOneBtn);
btn.setOnClickListener(new ButtonEvent());
return view;
}
private class ButtonEvent implements OnClickListener
{
#Override
public void onClick(View v)
{
// Create new fragment and transaction
Fragment newFragment = new CustomView();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_view, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
CustomView.java (uses custom_view.xml)
package com.example.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class CustomView extends Fragment
{
private TextView secondText;
private Button secondViewBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.custom_view,container,false);
return view;
}
}
In FirstView.java, when I click on the button, I need to move to the Fragment CustomView. But instead moving, it simply replaces everything in CustomView on top of FirstView. Below images will explain it better.
FirstView alone
CustomView alone
When the button is FirstView clicked
Why it is happening like this?
You are trying to replace firstView with the new fragment, but firstView is not a fragment, its' a RelativeLayout.
You cannot replace a fragment defined statically in the layout file. You can only replace fragments that you added dynamically via a FragmentTransaction.
None of your Layout contains fragment in layout.
<fragment
android:id="#+id/fragment1"
android:layout_width="march_parent"
android:layout_height="match_parent"></fragment>
A new Fragment will replace an existing Fragment that was previously added to the container.
Take look on this.
If you need to replace one fragment with another then fallow undermentioned :
TalkDetail fragment = new TalkDetail();
// TalkDetail is name of fragment which you need to put while replacing older one.
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("cat", m_ArrayList.get(arg2).cat);
bundle.putString("header_title", "Talk");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle); ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
Here's your BaseContainerFragment.java class that will manage a lot of stuff for you.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import app.drugs.talksooner.R;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
For more specific details find my complete post over here ..
Dynamically changing the fragments inside a fragment tab host?

Buttons within View Pager

I am trying to add buttons within a Fragment of PageView.
Please find attached the code that I am using for this application:
The specific code for the xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/banner_name"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:background="#drawable/button_banner"
android:gravity="center_vertical"
android:paddingLeft="10dip"
android:text="#string/equations"
android:textStyle="bold"
android:textColor="#ffffff" />
</LinearLayout>
<ScrollView
android:id="#+id/ScrollViewEquations"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/Button"
android:layout_width="fill_parent"
android:layout_height="25dip"
android:background="#drawable/custom_button"
android:gravity="center_vertical"
android:paddingLeft="25dip"
android:textColor="#516CE2"
android:text="#string/button" />
</LinearLayout>
</ScrollView>
</LinearLayout
this is the associated fragment code
package com.example.app;
import com.example.app![enter image description here][1].R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class EquationsMain extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.equations, container, false);
return view;
}
}
and this is the main code:
package com.example.app;
import com.example.app.R;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Window;
import android.view.WindowManager;
public class Main extends FragmentActivity {
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mAdapter = new MyAdapter(getSupportFragmentManager());
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new EquationsMain();
case 1:
return new MaterialsMain();
case 2:
return new AboutMain();
default:
return null;
}
}
}
}

Categories