android PagerTabStrip to start from left and not center - android

i have a pager tab strip in my project and when run on emulator or device it starts center like this
what i would like to achieve is to have the tab start left like this
I have tried layout graviity left in my xml but this is not working for me and i can't put my finger on how to resolve this, here is my xml with the pager tab strip.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<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="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="#drawable/gradient_bg"
android:textColor="#fff"
android:textSize="20sp"
android:id="#+id/tab_strip"
android:focusableInTouchMode="false">
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
</LinearLayout>
java code
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class MainActivity extends FragmentActivity {
//adview
ViewPager pager;
PagerTabStrip tab_strp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab);
ma_pager_adapter mapager=new ma_pager_adapter(getSupportFragmentManager());
pager=(ViewPager)findViewById(R.id.pager);
pager.setAdapter(mapager);
tab_strp=(PagerTabStrip)findViewById(R.id.tab_strip);
tab_strp.setTextColor(Color.WHITE);
// tab_strp.setTextSize(14,14);
// tab_strp.setTabIndicatorColor(Color.WHITE);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.firsteps);
mp.start();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
if(hasFocus){
ImageView welcomeText = (ImageView)findViewById(R.id.btsMainTextImage);
//welcomeText.animate().rotation(1440f).setDuration(2000);
}
}
#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.share) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.Locale;
//final MediaPlayer mp = MediaPlayer.create(this, R.raw.short_whoosh2);
public ma_pager_adapter(FragmentManager fm) {
super(fm);
}
//final MediaPlayer mp = MediaPlayer.create(this, R.raw.short_whoosh2);
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
tab1 t1 = new tab1();
return t1;
case 1:
tab2 t2 = new tab2();
return t2;
case 2:
tab4 t4 = new tab4();
return t4;
case 3:
tab3 t3 = new tab3();
return t3;
case 4:
tab5 t5 = new tab5();
return t5;
}
return null;
}
#Override
public int getCount() {
return 5;
}//set the number of tabs
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Tab1";
case 1:
return "Tab2";
case 2:
return "Tab3";
case 3:
return "Tab4";
case 4:
return "Tab5";
}
return null;
}
}

That is not possible with PagerTabStrip and ToolBar. Since ActionBarTabs have been deprecated, use a TabLayout.

Here is the Code that how you can use TabLayout easily.
Here is the output that you will get.
main_activty.xml or any of your XML file where your want to use these Tabs and Viewpager
<android.support.design.widget.AppBarLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" android:id="#+id/appBarLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#f9f8f8"
app:tabSelectedTextColor="#fff"
app:tabGravity="fill"
app:tabMode="fixed"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="left"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
</android.support.v4.view.ViewPager>
That XML code should work for you. For the complete code, you can visit here - https://tutorialvilla.com/how/how-to-use-tablayout-and-viewpager-in-android-kotlin

Related

Fragment is not being replaced after click in navigation drawer

I tried every way to solve this problem but still I am not getting whats wrong with this code. Can you help me?
My mainpage activity is as
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class MainPage extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private FragmentTransaction fragmentTransction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_page);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mNavigationView=findViewById(R.id.idnav_view);
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout=findViewById(R.id.iddrawer_layout);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment frag=null;
int itemId=menuItem.getItemId();
if(itemId==R.id.id_nvHome){
frag=new HomeFragment();
}
else if(itemId==R.id.id_nvSearch){
frag=new SearchFragment();
}
Toast.makeText(getApplicationContext(),menuItem.getTitle(),Toast.LENGTH_SHORT).show();
if(frag!=null){
FragmentTransaction transction=getSupportFragmentManager().beginTransaction();
transction.replace(R.id.idcontent_frame,frag);
transction.commit();
mDrawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and for mypage activity layout is
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/iddrawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/idcontent_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<android.support.design.widget.NavigationView
android:id="#+id/idnav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
my homefragment is as
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_home,container,false);
return v;
}
}
and also layout for that is as
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_marginTop="150dp"
android:layout_marginLeft="150dp"
android:textColor="#000000"
android:textSize="30dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
I want to REPLACE FRAGMENT WITH OTHER FRAGMENT WHEN I CLICK ON NAVIGATION DRAWER ITEMS
Can anyone help me?
I can support you giving you my working code for Android 27.1.1:
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
private int mSelectedId;
/**
* Create Navigation bar and load the main fragment "statistics".
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new FragmentStatistics());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
mSelectedId = navigation.getSelectedItemId();
}
/**
* Checks for any event in the Navigation Bar.
* If the item selected is the same as the actual item
* Do nothing
* Else
* Load new fragment selected.
*/
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
if (mSelectedId != item.getItemId()) {
mSelectedId = item.getItemId();
switch (item.getItemId()) {
case R.id.statistics:
fragment = new FragmentStatistics();
break;
case R.id.shops:
fragment = new FragmentShops();
break;
}
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
The rest of your code is exact as mine.

set the Actionbar in TabHost Activity of android?

I am trying to set the ActionBar to a tab activity in android. i tried a lot.
But can't solve this topic. i'm using the Tab Activity, i want to display actionbar above the tabhost. How can I add actionbar in this activity?
I'm using the android studio and sdk is 25
here is my code:
package com.example.lenovo.monitoringapp;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
public class KwhActivity extends TabActivity {
TabHost TabHostWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kwh);
TabHostWindow = (TabHost) findViewById(android.R.id.tabhost);
TabSpec TabMenu1 = TabHostWindow.newTabSpec("Graph");
TabSpec TabMenu2 = TabHostWindow.newTabSpec("Data List");
TabMenu1.setIndicator("Graph");
Intent intent = new Intent(KwhActivity.this, GraphActivity.class);
// intent.putExtra("uname", username);
// Set tab 1 activity to tab 1 menu.
TabMenu1.setContent(intent);
// Setting up tab 2 name.
TabMenu2.setIndicator("Data List");
Intent i1 = new Intent(KwhActivity.this, DataListActivity.class);
// i1.putExtra("uname", username);
// Set tab 3 activity to tab 1 menu.
TabMenu2.setContent(i1);
TabHostWindow.addTab(TabMenu1);
TabHostWindow.addTab(TabMenu2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kwhactivity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_other1:
AlertDialog.Builder builderSingle = new AlertDialog.Builder(KwhActivity.this);
builderSingle.setIcon(R.drawable.calender);
builderSingle.setTitle("Select");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(KwhActivity.this, android.R.layout.select_dialog_item);
arrayAdapter.add("Today");
arrayAdapter.add("Yesterday");
arrayAdapter.add("Week");
arrayAdapter.add("30 Days");
arrayAdapter.add("Year");
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
if(strName == "Today")
{
Toast.makeText(KwhActivity.this, "Today!",
Toast.LENGTH_LONG).show();
}
}
});
builderSingle.show();
break;
default:
break;
}
return false;
}
}
Here is activity_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:scrollbars="vertical"
android:background="#drawable/rounded_edittext"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_height="30dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
Use Toolbar above TabHost by using below code;
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />

Tabs not visible but navigation on swipe works in TabLayout

I am trying to create an app with 3 simple tabs using tabbed activity. I created a project with tabbed activity then I removed the auto generated static Fragment class and created 3 fragment classes as well as fragment layouts and used them in FragmentPagerAdapter.
Tabs are working, I can swipe between the tabs, but I am not able to see the TAB headers on the top.
Any suggestion ?
MainActivity.java
package com.kbsoft.tabbedtest;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
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) {
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "TAB 1";
case 1:
return "TAB 2";
case 2:
return "TAB 3";
}
return null;
}
}
}
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.kbsoft.tabbedtest.MainActivity">
<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"
android:background="?attr/colorPrimary"
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.CoordinatorLayout>
Tab1.java
package com.kbsoft.tabbedtest;
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.fragment_main, container, false);
return rootView;
}
}
fragment_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="com.kbsoft.tabbedtest.MainActivity">
<TextView
android:id="#+id/section_label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text1" />
</RelativeLayout>
All other fragment classes and fragment layouts are identical.

fragment text appearing in toolbar

I'm trying to get a sliding drawer set up. I want the text to appear in the main body of the activity, but instead it's appearing inside of the toolbar, and it only says This is fragment 2, regardless of whether I pulled up the fragment that's supposed to say This is fragment 1 or This is fragment 2.
How can I make it pull up the proper fragment, instead of always fragment 2, and how can I make the toolbar opaque, with text appearing under it instead of in it.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
tools:context="me.paxana.alerta.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="8dp"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:layout_alignParentTop="true">
</RelativeLayout>
<ListView
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="#+id/lv_sliding_menu"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java
package me.paxana.alerta;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.paxana.alerta.adapter.SlidingMenuAdapter;
import me.paxana.alerta.fragment.Fragment1;
import me.paxana.alerta.fragment.Fragment2;
import me.paxana.alerta.fragment.Fragment3;
import me.paxana.alerta.model.ItemSlideMenu;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private android.support.v7.app.ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
}
else {
Log.i(TAG, currentUser.getUsername());
}
listViewSliding = (ListView)findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//add item for sliding list
listSliding. add(new ItemSlideMenu(R.drawable.ic_action_settings, "Settings"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, "About"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_logout_black_48dp, "Log Out"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//item selected
listViewSliding.setItemChecked(0, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
//handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
ParseUser.logOut();
navigateToLogin();
} else {
//replace fragment
replaceFragment(position);
//item selected
listViewSliding.setItemChecked(position, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
}
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
fragment = new Fragment1();
break;
}
if(null != fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
I solved one part of this issue, though I'm not certain I used best practices. I added padding to the top of main_content in a size of "?attr/actionBarSize"
But it's still only displaying This is Fragment 2, regardless of which fragment I'm trying to select.
If you want the content below the toolbar, you can wrap toolbar and content in one layout as:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:background="#8000ff00"
>
</RelativeLayout>
</LinearLayout>
Besides, if you are using Android Studio, creating Navigation Drawer Activity through the wizard is the best way to ensure that everything works properly.

Fragments still visible after calling replace method

I know this has other answers but I've looked around and tried other solutions; all of which did not work.
I have a menu with items that are clickable; and when clicked they replace a Fragment on the main screen with another Fragment.
Here is my code:
package com.nanospark.cnc;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
//import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
GridLayout_Fragment profileGridFragment = new GridLayout_Fragment();
EventList_Fragment eventListFragment = new EventList_Fragment();
ContactList_Fragment contactListFragment = new ContactList_Fragment();
FragmentManager transactionManager = getSupportFragmentManager();
FragmentTransaction transaction;
//CustomIOIO customioio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, profileGridFragment);
transaction.commit();
}
//insert the initial fragment for when the app boots.
/* customioio = (CustomIOIO) getApplicationContext();
customioio.create();
customioio.start();*/
}
#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
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
openSettings();
return true;
case R.id.action_home:
openHome();
return true;
case R.id.action_events:
openEvents();
return true;
case R.id.action_help:
openHelp();
return true;
case R.id.action_contacts:
openContacts();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openContacts() {
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, contactListFragment);
transaction.commit();
}
private void openHome() {
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, profileGridFragment);
transaction.commit();
}
private void openHelp() {
}
private void openEvents() {
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, eventListFragment);
transaction.commit();
}
private void openSettings() {
}
}
I am not sure as to why the previous Fragments are still visible?
EDIT - adding my activiy_main.xml layout file:
<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="com.nanospark.cnc.MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
</RelativeLayout>

Categories

Resources