Add ExpandableListView in Tabs - java

This is my problem:
I have created a four-tabs application (named: Day 1, Day 2, Day 3 and Day 4) and each tab has a layout. The problem is that this layout can contain only Text Views and strings, but I need to insert a more complex ExpandableListView with its own java class in each Tab, the result I would like is something like the "contacts" application.
My main activity is:
package tabs;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener
// for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mCollectionPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class CollectionPagerAdapter extends FragmentPagerAdapter {
final int NUM_ITEMS = 4; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.title_section1);
break;
case 1:
tabLabel = getString(R.string.title_section2);
break;
case 2:
tabLabel = getString(R.string.title_section3);
break;
case 3:
tabLabel = getString(R.string.title_section4);
break;
}
return tabLabel;
}
}
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
case 3:
tabLayout = R.layout.tab4;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}}
The main xml layout is
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
The Tabs layout is (they all are the same but with different texts, this one is just "hello")
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="one" />
</LinearLayout>

Related

Data reset when moving from one to another fragment using Bottom Navigation Bar

I am using bottom navigation bar dan fragment in my project.
When it moved from one to another fragment, I dont want to lose the state or data
How can I do it?
This is activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F9FAFD">
<FrameLayout
android:id="#+id/page_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_bar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:background="#android:color/white"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_menu" />
</RelativeLayout>
And this is the MainActivity.java
package com.noval.tugas_6;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.noval.tugas_6.computer.ComputerFragment;
import com.noval.tugas_6.home.HomeFragment;
import com.noval.tugas_6.home_services.HomeServicesFragment;
import com.noval.tugas_6.phone.PhoneFragment;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
private Fragment fragment;
private long exitTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_bar);
getFragmentPage(new HomeFragment());
setBottomNavigationView();
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
private boolean getFragmentPage(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.addToBackStack(null)
.replace(R.id.page_fragment, fragment)
.commit();
return true;
}
return false;
}
#Override
public void onBackPressed() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
}
This is one of the fragment that I am using
PhoneFragment.java
package com.noval.tugas_6.phone;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.noval.tugas_6.R;
public class PhoneFragment extends Fragment {
public int[] imgID = new int[]{R.drawable.infinix_zero, R.drawable.realme_c35,
R.drawable.galaxy_a33, R.drawable.samsung_galaxy_a13, R.drawable.samsung_galaxy_a23};
public String[] namaHP = new String[]{"Infinix Zero 5G", "Realme C35", "Samsung Galaxy A33 5G",
"Samsung Galaxy A13", "Samsung Galaxy A23"};
public String[] hargaHP = new String[]{"Rp3.600.000", "Rp2.150.000", "Rp4.700.000", "Rp2.500.000", "Rp3.500.000"};
ImageView imgHP;
TextView txtNama, txtHarga;
Button btnNext, btnPrevious;
int position = 0;
public PhoneFragment() {
// Required empty public constructor
}
// public static PhoneFragment newInstance() {
// PhoneFragment fragment = new PhoneFragment();
// Bundle args = new Bundle();
// fragment.setArguments(args);
// return fragment;
// }
//
// #Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (getArguments() != null) {
//
// }
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
// method ini dipanggil sesaat setelah onCreateView di atas dipanggil
// semua pembacaan view dan penambahan listener dilakukan disini
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
imgHP = (ImageView) getActivity().findViewById(R.id.imgHP);
txtNama = (TextView) getActivity().findViewById(R.id.txtNamaHP);
txtHarga = (TextView) getActivity().findViewById(R.id.txtHargaHP);
btnNext = (Button) getActivity().findViewById(R.id.btnNextHP);
btnPrevious = (Button) getActivity().findViewById(R.id.btnPreviousHP);
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
btnPrevious.setVisibility(View.GONE);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
position += 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
// jika posisi item yang terakhir, hilangkan tombol next
if (position == (imgID.length - 1)) {
btnNext.setVisibility(View.GONE);
} else if (position > 0) {
btnPrevious.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
position -= 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
if (position == 0) {
btnPrevious.setVisibility(View.GONE);
} else {
btnNext.setVisibility(View.VISIBLE);
}
}
});
}
}
Please show me how to not lose the fragment data when moving to another fragment
Thanks
because every time user click on navigation bottom u create new instance of fragment every time :
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
try this :
private homeFragment = new HomeFragment();
private computerFragment = new ComputerFragment();
private phoneFragment = new PhoneFragment();
private homeServicesFragment = new HomeServicesFragment();
private Fragment active;
private final FragmentManager fm = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
initFragment();
...
}
private void changeFragment(Fragment fragment, Bundle bundle) {
fm.beginTransaction()
.hide(active)
.show(fragment)
.commit();
active = fragment;
active.setArguments(bundle);
}
private void initFragment() {
fm.beginTransaction().add(R.id.frameLayout, homeFragment, homeFragment.class.getSimpleName()).commit();
fm.beginTransaction().add(R.id.frameLayout, computerFragment, computerFragment.class.getSimpleName()).hide(computerFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, phoneFragment, PhoneFragment.class.getSimpleName()).hide(phoneFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, homeServicesFragment, HomeServicesFragment.class.getSimpleName()).hide(homeServicesFragment).commit();
active = homeFragment;
changeFragment(homeFragment, null);
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
changeFragment(homeFragment, null);
return true;
case R.id.computer_menu:
changeFragment(computerFragment, null);
return true;
case R.id.phone_menu:
changeFragment(phoneFragment, null);
return true;
case R.id.home_services_menu:
changeFragment(homeServicesFragment, null);
return true;
}
return homeFragment;
}
});
}

fragment open the layout_activity

hi i have a big problem with this type of programming i cannot open the layout into fragment, this is my code.
i need to know what i have to insert into main.java for open the tooldadi.java and toolnomi.java to se the proper layout. thanks a lot this site is the best.
tooldadi.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by ferdinandoargenzio on 23/07/15.
*/
public class tooldadi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.tooldadi_layout, container, false);
}
}
toolnomi.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by ferdinandoargenzio on 23/07/15.
*/
public class toolnomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.toolnomi_layout, container, false);
}
}
tooldadi_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tool dadi"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
tooldadi_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tool nomi"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Main.java
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class Main extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given 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);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Main) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
I think you are making things complex. And I don't see binding instances of fragments to Main. Make the following changes:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new tooldadi();
mTitle = getString(R.string.title_section1);
break;
case 1:
fragment = new toolnomi();
mTitle = getString(R.string.title_section2);
break;
case 2:
mTitle = getString(R.string.title_section3);
break;
case 3:
mTitle = getString(R.string.title_section4);
break;
case 4:
mTitle = getString(R.string.title_section5);
break;
case 5:
mTitle = getString(R.string.title_section6);
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
However, I would suggest using NewInstance method for individual fragments instead of directly calling new on them to avoid intermittent crashes.

Swipe without tab content overlapping

I have created a swipe view with tabs, but when swiping between tabs, the content that was in the tab will slide with your finger, and the previous tabs' content will overlap with the tab being swiped in.
For example:
Here's my MainActivity.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
Fragment tab1Fragment = new Tab1();
Fragment tab2Fragment = new Tab2();
Fragment tab3Fragment = new Tab3();
ViewPager mViewPager;
private TabsPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
getSupportActionBar().setSelectedNavigationItem(position);
}
});
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Instantiate the tabs.
tab1 = actionBar.newTab();
tab2 = actionBar.newTab();
tab3 = actionBar.newTab();
//Set the tabs' text.
tab1.setText("Tab 1");
tab2.setText("Tab 2");
tab3.setText("Tab 3");
//Setting up the tab listeners
tab1.setTabListener(new MyTabListener(tab1Fragment));
tab2.setTabListener(new MyTabListener(tab2Fragment));
tab3.setTabListener(new MyTabListener(tab3Fragment));
//Adding tabs to the ActionBar
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#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);
}
}
MyTabListener.java:
import android.support.v4.app.Fragment;
public class MyTabListener implements android.support.v7.app.ActionBar.TabListener {
private Fragment fragment;
public MyTabListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
ft.add(android.R.id.content, fragment);
ft.attach(fragment);
}
#Override
public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
ft.remove(fragment);
}
#Override
public void onTabReselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
}
Tab1.java (Tab2.java and Tab3.java are similar):
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_layout, container, false);
return rootView;
}
}
TabsPagerAdapter.java:
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
activity_main.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
tab1_layout.xml (tab2_layout.xml and tab3_layout.xml are similar):
<?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"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is tab 1."/>
</LinearLayout>
I tried adding a background color in the tab XML layout files, but then there would be no sliding animation at all. My Android version is 4.4.2, I don't know if the issue is related to that. How can I solve this so that the tabs swipe without overlapping content with the previous tab?
See explanation given on Developer site - adding tabs with swipe view
don't call add() or attach methods but do like this:
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
You may want to consider using the new support design library, the new TabLayout makes writing swipe layouts easier and since ActionBar tabs are now deprecated by Google.
https://github.com/codepath/android_guides/wiki/Google-Play-Style-Tabs-using-TabLayout
In your class MyTabListener change
android.R.id.content
by this
R.id.action_bar_activity_content
Which android support library are you using? This problem was fixed in Support Library v19?
Here you have more information about this

Adding tabs below the action bar

In my android application I have implemented a tab layout with swipeable views. Here is my MainActivity class:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class CustomerComplainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "New Complain", "Previous Complains" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
And this is my TabPager Adapter class:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new NewComplain();
case 1:
return new PreviousComplains();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
This is my activity_main.xml file.
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AdminMainActivity" >
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#800000"
android:paddingBottom="4dp"
android:paddingTop="5dp"
android:textColor="#fff"
android:textSize="18dp" />
This works, but the problem is the tabs are adding into the actiob bar as following.
But I want to add these tabs below the action bar. I would be much appreciated if anyone plz be so kind enough to explain how can I solve this problem.
Thanx in advance
I have same issue. I found the solution by replacing this line
actionBar.setHomeButtonEnabled(false);
with
actionBar.setDisplayShowHomeEnabled(true);
and your problem is solved.

Launch a activity with button click using a FragmentActivity

Hey guys I need help I'm making a launcher that needs to have a button that when clicked it opens the AllApps.class activity witch shows a list of all installed apps
The other button needs to open a installed app that is on the device
and the last button needs to open the default web browser and open google.com
Here's my code!
Home.java:
package com.dva.schooltoolshome;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
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.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class Home extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
^ ActionBar.DISPLAY_SHOW_TITLE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("calc")) {
actionBar.addTab(actionBar.newTab()
.setIcon(R.drawable.calendar)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("home")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.home)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("drive")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.folder)
.setTabListener(this));
}
}
mViewPager.setCurrentItem(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_SETTINGS));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CalcFragment();
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new DriveFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class HomeFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_homebar,
container, false);
return rootView;
}
}
public static class CalcFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public CalcFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_calculator,
container, false);
return rootView;
}
}
public static class DriveFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DriveFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("DRIVE");
return rootView;
}
}
}
activity_homebar
<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:background="#drawable/bg"
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=".HomeBar" >
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/apps"
android:src="#drawable/browser" />
</RelativeLayout>
AllApps.java:
package com.dva.schooltoolshome;
import android.app.LauncherActivity;
import android.content.Intent;
public class AllApps extends LauncherActivity {
#Override
protected Intent getTargetIntent () {
// just a example, you should replace the method yourself
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
I'm am still learning so please don't judge
Thanks in advance
Regards
Rapsong11
You can easily find the answer to your question with a bit of googling. It has been asked many times before. I will point you in the right direction.
To add functionality to a button you have to first make the button (view) aware it can be clicked. This can be done in java programatically (research this yourself) or in the xml like so:
android:onClick="onClickDoStuff"
Then you have to implement the onClickDoStuff method which will look like:
public void onClickDoStuff(View view) {
//Do stuff on click
}
You wanted the button to open a new activity onClick to do that you would require an intent have a look here for futher guidance

Categories

Resources