Change layout in Navigation Drawer - android

I have a basic app with a sidebar view. Now I want to be able to change the layout by clicking on one of the items in the navigation drawer. How can I do that?
For example i want to get to the layout "layout_gallery" by clicking on "Gallery" in the navigation drawer.
Here's the code of the MainActivity.java:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thanks in advance

Try this one:
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.orgName.myName.projectName.MainActivity" >
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/main_container"
layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"
android:visibility="gone"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add"
android:visibility="gone"/>
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.orgName.myName.projectName.MainActivity"
tools:showIn="#layout/app_bar_main">
<LinearLayout
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"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_main, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_gallery) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_gallery, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_slideshow) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_slideshow, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_manage) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_manage, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_share) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_share, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_send) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_send, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

Use fragment for multiple classes and layout.
You can find an example here

Related

Action Bar title and navigation drawer icon missing

In MainPage, it has NavigationDrawer and BottomNavigationBar. When I clicked Home, the navigation drawer icon and action bar title missing.
MainPage
public class MainPage extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomePage();
loadFragment(fragment);
return true;
case R.id.navigation_dashboard:
return true;
case R.id.navigation_notifications:
return true;
}
return false;
}
};
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the main; 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.rl, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
HomePage
public class HomePage extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.app_bar_main, container, false);
RecyclerView mRecyclerView = view.findViewById(R.id.recycleView);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
List <Book> bookList= new ArrayList<>();
Book book = new Book();
book = new Book("Introduction to Java Programming", 15.00, "4.5", Uri.parse("android.resource://com.example.seng.sechandapp/drawable/book").toString());
bookList.add(book);
book = new Book("Java", 15.00, "4.5", Uri.parse("android.resource://com.example.seng.sechandapp/drawable/book").toString());
bookList.add(book);
HomePageAdapter homePageAdapter = new HomePageAdapter(getActivity(), bookList);
mRecyclerView.setAdapter(homePageAdapter);
return view;
}
}
app_bar_main
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.seng.sechandapp.MainPage">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
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="#color/blueviolet"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/home_page"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
home_page
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycleView">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
Try this
Make below Changes in you code
First Change
Use this in your HomePage Fragment
View view = inflater.inflate(R.layout.home_page, container, false);
instead of
View view = inflater.inflate(R.layout.app_bar_main, container, false);
Second Change
Now in your home_page add android:layout_marginTop="?actionBarSize" in your FrameLayout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_marginTop="?actionBarSize"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Some Other suggestion
Use implementation instead of compile in your build.gradle
because
Configuration compile is obsolete and has been replaced with implementation.
It will be removed at the end of 2018
You are inflating app_bar_main.xml instead of home_page.xml inside the Fragment. Replace View view = inflater.inflate(R.layout.app_bar_main, container, false); with View view = inflater.inflate(R.layout.home_page, container, false);. And where is the view with ID R.id.rl?

How to make a Tabs Fragment inside Navigation Drawer Fragment? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a navigation drawer with two items(each item is a fragment)
The first item "import" ,should display this Fragment:
Here is the Fragment class:
public class Import extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.import_main,container,false);
}
}
it's layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark">
</android.support.constraint.ConstraintLayout>
The second item "Gallery",should display a TabsLayout that contains 2 fragments (TabLeft and TabRight) :
Here is it's classe:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tabs,container,false);
}
and the layout:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_id"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="left"/>
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="right"/>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/pager" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I have tried to implement that but i get a weird error which is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abzo.fragmentstut/com.example.abzo.fragmentstut.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
Here is my MainActivity code:
package com.example.abzo.fragmentstut;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
////////
TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_id);
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
TabPagerAdapter tabsAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAdapter);
//tabLayout.setupWithViewPager(viewPager);
/////
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
getSupportFragmentManager().beginTransaction().replace(R.id.content_main, new Import()).commit();
} else if (id == R.id.nav_gallery) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_main, new Tabs()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My TabPagerAdapter:
package com.example.abzo.fragmentstut;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter {
String [] pagetitle = new String []{"one","two"};
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
TabOne one= new TabOne();
return one;
case 1:
TabTwo two= new TabTwo();
return two;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
and here is one of the 2 tab classes (fragments): (the 2nd tab class is similar)
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_left,container,false);
}
Try this one
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
TabOne one= new TabOne();
return one;
deafault:
TabTwo two= new TabTwo();
return two;
}
}
You have to return Fragment here not null. Always try to use default in switch

RecyclerView not showing anything, although there not seem to be any problems

I am a bit comfused at this moment. In order to save time I used Android Studio's template for Navigation Drawer Activity. I was planning to create a Navigation Drawer and pass it through the rest of the activities. The first Activity did go well. The problem is with the second one, as I want to have the Navigation Drawer and create a RecyclerView.
So my code is:
Content_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.sparrowred.sendcard.Main2Activity"
tools:showIn="#layout/activity_main2">
<android.support.v7.widget.RecyclerView
android:id="#+id/imageRecycleView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
app_bar_main2.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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.sparrowred.sendcard.Main2Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main2" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_menu_add" />
</android.support.design.widget.CoordinatorLayout>
nav_header_main2.xml
<?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="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
image_list_row:
<?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="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:contentDescription="#string/image_descrprtion"
android:layout_gravity="center_horizontal"
android:id="#+id/imageId"
android:src="#drawable/profile"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textStyle="bold"
android:padding="8dp"
android:layout_gravity="center_horizontal"
android:text="dummy"/>
</LinearLayout>
imageAdapter.java:
package com.sparrowred.sendcard;
public class imageAdapter {
private String title;
private int imageId;
public imageAdapter() {
}
public imageAdapter(String title, int imageId) {
this.title = title;
this.imageId = imageId;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setImageId(int imageId){
this.imageId = imageId;
}
public int getImageId(){
return this.imageId;
}
}
imageDescriptionArray.java (I need to change the name :P):
package com.sparrowred.sendcard;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class imageDescriptionArray extends RecyclerView.Adapter<imageDescriptionArray.MyViewHolder> {
private LayoutInflater layoutInflater;
private List<imageAdapter> imageAdapterList;
public imageDescriptionArray(List<imageAdapter> imageAdapterList) {
this.imageAdapterList = imageAdapterList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.image_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
imageAdapter iva = imageAdapterList.get(position);
holder.title.setText(iva.getTitle());
holder.image.setImageResource(iva.getImageId());
}
#Override
public int getItemCount() {
return imageAdapterList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
image = (ImageView) view.findViewById(R.id.imageId);
}
}
}
and finally Main2Activity.java:
package com.sparrowred.sendcard;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import jp.wasabeef.recyclerview.animators.SlideInUpAnimator;
public class Main2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private RecyclerView mImageRecycleView;
private List<imageAdapter> imageAdapterList;
private imageDescriptionArray mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mImageRecycleView = (RecyclerView) findViewById(R.id.imageRecycleView);
mImageRecycleView.setHasFixedSize(true);
imageAdapterList = new ArrayList<>(12);
mAdapter = new imageDescriptionArray(imageAdapterList);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mImageRecycleView.setLayoutManager(mLayoutManager);
mImageRecycleView.setItemAnimator(new SlideInUpAnimator());
mImageRecycleView.setAdapter(mAdapter);
prepareData();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void prepareData(){
List<imageAdapter> data = new ArrayList<>();
int[] images = {R.drawable.birthday_image_1,R.drawable.birthday_image_2,R.drawable.birthday_image_3,R.drawable.birthday_image_4,
R.drawable.birthday_image_5,R.drawable.birthday_image_6,R.drawable.birthday_i mage_7,R.drawable.birthday_image_8,
R.drawable.birthday_image_9,R.drawable.birthday_image_10,R.drawable.birthday_ image_11,R.drawable.birthday_image_12};
String[] description = {"ballons","a lot of cakes","ballons with cakes","presents","presents with hat","cup-cake",
"retro","perspective","flying presents","empty card","giving a present","tasty cake"};
for(int i = 0; i<images.length && i<description.length; i++){
imageAdapter current = new imageAdapter();
current.setTitle(description[i]);
current.setImageId(images[i]);
data.add(current);
}
mAdapter.notifyDataSetChanged();
}
}
This the code for my second activity.It's not fully implemented but for sure the recyclerView doesn't work. Can anyone help me out with this. I believe that the problem is within my xmls .... but I cannot find anything.
PS. My code, when compiled shows no errors....
Try with the following code. Replace your prepareData() with mine
private void prepareData(){
int[] images = {R.drawable.birthday_image_1,R.drawable.birthday_image_2,R.drawable.birthday_image_3,R.drawable.birthday_image_4,
R.drawable.birthday_image_5,R.drawable.birthday_image_6,R.drawable.birthday_i mage_7,R.drawable.birthday_image_8,
R.drawable.birthday_image_9,R.drawable.birthday_image_10,R.drawable.birthday_ image_11,R.drawable.birthday_image_12};
String[] description = {"ballons","a lot of cakes","ballons with cakes","presents","presents with hat","cup-cake",
"retro","perspective","flying presents","empty card","giving a present","tasty cake"};
for(int i = 0; i<images.length && i<description.length; i++){
imageAdapter current = new imageAdapter();
current.setTitle(description[i]);
current.setImageId(images[i]);
imageAdapterList.add(current);
}
mAdapter.notifyDataSetChanged();
}

Change layout with Navigation Drawer

When I start a new "Navigation Drawer" project in Android Studio there is already some code. How can I change the layout by using the Buttons in the Drawer?
The Navigation Drawer looks like this
Try this code:
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout >
app_bar_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.orgName.myName.projectName.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/main_container"
layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"
android:visibility="gone"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add"
android:visibility="gone"/>
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.orgName.myName.projectName.MainActivity"
tools:showIn="#layout/app_bar_main">
<LinearLayout
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"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_main, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_gallery) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_gallery, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_slideshow) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_slideshow, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_manage) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_manage, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_share) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_share, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_send) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_send, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
look your MainActivity XML, you will find the structure likes below:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- you can custom your layout here in LinearLayout-->
<LinearLayout android:id="#+id/navigation_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" >
<!-- you can add a button here-->
<Button
android:id="#+id/Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mButton"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
you can custom your view in fragment, or instead with a Linearlayout here and fill button in your layout.
mLinearLayout = (LinearLayout) findViewById(R.id.navigation_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mButton = (DrawerLayout) findViewById(R.id.Button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//close DrawerLayout here
mDrawerLayout.closeDrawer(mLinearLayout);
}
});
You can use a Fragment to replace FrameLayout:
FragmentTransaction fragmentTransaction1 = fragmentManager
.beginTransaction();
fragmentTransaction1.replace(R.id.content_frame,
overviewFragment);
fragmentTransaction1.commit();

Unable to set textView and custom background in gridview items

I 'am developing an app that has a gridview with 10 imageButtons.Now i have implemented a method called SquareImageView to adjust the number of columns to 2 irrespective of the screen size.I don't know how to put the texts inside this.
My present application is this:
As you can see there are just images in the grid.I want to give a border,and some text in each of those image in the center bottom.Some thing like this
my files are:
package com.defcomdevs.invento16;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private CollapsingToolbarLayout mcollapsingToolbar;
private NestedScrollView mnestedScrollView;
private CoordinatorLayout coordinatorLayout;
private DrawerLayout drawerLayout;
int backButtonCount = 0;
private Button button;
GridView mygrid;
private ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);
coordinatorLayout.setBackground(getResources().getDrawable(R.drawable.oppo));
// drawerLayout.setBackground(getResources().getDrawable(R.drawable.oppo));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//button= (Button) findViewById(R.id.setalarm);
mcollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
//mnestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
mcollapsingToolbar.setTitle("INVENTO '16");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
callRegister();
}
});
mygrid= (GridView) findViewById(R.id.gridView);
mygrid.setAdapter(new MizAdapter(this));
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void callRegister() {
Intent intent = new Intent(this, Registration.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (backButtonCount >= 1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
/* public void setalarm(View view){
if(view.getId()==R.id.setalarm){
Intent intent=new Intent(this,AlarmActivity.class);
startActivity(intent);
}
}*/
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.about_college) {
// Handle the camera action
} else if (id == R.id.cse) {
} else if (id == R.id.it) {
} else if (id == R.id.ece) {
} else if (id == R.id.mech) {
} else if (id == R.id.Coding) {
Intent intent = new Intent(this, Coding.class);
startActivity(intent);
} else if (id == R.id.Hacking) {
} else if (id == R.id.printing) {
} else if (id == R.id.Big) {
} else if (id == R.id.nand) {
} else if (id == R.id.cryo) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class itemName{ //Since we have to bounr the image to the item with the name and the subtitle
//we keep all information inside the class and deal with the class entirely
String Iname;
int ImageId;
itemName(String name,int imageId){
Iname=name;
ImageId=imageId;
}
}
class MizAdapter extends BaseAdapter{
ArrayList<itemName> items;
Context context;
MizAdapter(Context context){
this.context=context;
items=new ArrayList<itemName>(); //initialize each item with the type itemName.
Resources res=context.getResources();
String[] itemnames=res.getStringArray(R.array.Items);
int[] itempics={R.drawable.hackbttn100,R.drawable.hackbttn100,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn};
for(int i=0;i<10;i++){
itemName names=new itemName(itemnames[i],itempics[i]);
items.add(names);
}
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder{
ImageButton myImage;
ViewHolder(View v){
myImage= (ImageButton) v.findViewById(R.id.picture);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
ViewHolder viewHolder=null;
if (row==null){
LayoutInflater inflater= (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.singleitem, parent, false);
viewHolder=new ViewHolder(row);
row.setTag(viewHolder);
}
else {
viewHolder= (ViewHolder) row.getTag();
}
itemName temp=items.get(position);
viewHolder.myImage.setImageResource(temp.ImageId);
return row;
}
public void coding(View v){
}
}
}
Following is to set the numbers of columns to 2 irrespective of screen size.
package com.defcomdevs.invento16;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;
/**
* Created by midhun on 23/10/15.
*/
public class SquareImageView extends ImageButton {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
My mainactivity.xml file
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/app_bar"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="196dp"
android:background="#3f51b5"
app:contentScrim="#color/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/index"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.widget.NestedScrollView>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginTop="198dp"
android:id="#+id/gridView"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:numColumns="2"
android:stretchMode="columnWidth"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
Now each ImageButton has a common layout xml file for it
<?xml version="1.0" encoding="utf-8"?>
<com.defcomdevs.invento16.SquareImageView
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:onClick="coding"
android:background="#drawable/custom_button"/>
Also here i want to define a custom background to all these imagebuttons so that when the user clicks the button a slight transparent color(any color) comes over the image below.
please help me out.
Why not use a separate layout for the grid view layout. So that each button would actually be a layout with a parent layout ie RelativeLayout and Inside the layout you have two child views. One the text view which has a gravity parameter to the bottom. Then the picture as the background of the parent layout.
Use this layout as the Adapters layout. It will recreate it for each item you want.

Categories

Resources