Unable to set textView and custom background in gridview items - android

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.

Related

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

Having trouble loading a Listview on a Fragment called from a Navigation menu item

i am new into android programming. I am having difficulty showing a Listview on a ListFragment. I've already tried it on an activity and it worked perfectly, however,i tried displaying the same listview on a Listfragment called from a Navigation Drawer but my app crashes on item click. I have been on it for so long, tried getting answers from different websites but all to no avail.
Pls: A little help would be nice and much appreciated
The error displayed on the logcat is:
09-18 14:35:53.285
3602-3602/com.example.ceede.classwork E/AndroidRuntime: FATAL
EXCEPTION: main Process: com.example.ceede.classwork, PID: 3602
java.lang.NullPointerException at
com.example.ceede.classwork.MainActivity.onNavigationItemSelected(MainActivity.java:92)
at
android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:152)
content_main.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.example.ceede.classwork.MainActivity"
tools:showIn="#layout/app_bar_main">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="android.support.v4.app.ListFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
CustomAdapter.java
package com.example.ceede.classwork;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
CustomAdapter(Context context) {
list = new ArrayList<>();
this.context = context;
Resources res = context.getResources();
String[] titles = res.getStringArray(R.array.Titles);
int[] images = {R.drawable.admisntrationicon, R.drawable.articon, R.drawable.businesseducationicon,
R.drawable.homeicon, R.drawable.drivericon, R.drawable.stafficon,
R.drawable.counciloricon, R.drawable.physicalcon, R.drawable.englishicon,
R.drawable.mathsicon, R.drawable.scienceicon, R.drawable.historyicon,
R.drawable.suporticon};
for (int i = 0; i < titles.length; i++) {
list.add(new SingleRow(titles[i], images[i]));
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
SingleRow temp = list.get(i);
View row = null;
if(view==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.single_row,viewGroup,false);
}
TextView titles= (TextView) row.findViewById(R.id.textAdmin);
ImageView image= (ImageView)row.findViewById(R.id.adminImage);
return row;
}
}
SingleRow.java
class SingleRow {
public String titles;
public int images;
SingleRow(String titles, int images) {
this.titles = titles;
this.images = images;
}
}
MyFragmentClass.java
package com.example.ceede.classwork;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class MyFirstFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_list_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView= (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(new CustomAdapter(getActivity()));
}
public static Fragment newInstance() {
MyFirstFragment frag=new MyFirstFragment();
return frag;
}
}
MainActivity
package com.example.ceede.classwork;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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 {
FragmentManager manager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
}
#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.contact) {
// Handle the camera action
//Line 92. This is the Line of code causing the error
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.fragment, MyFirstFragment.newInstance());
transaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You should not initialize FragmentManager and call beginTransaction in onCreate. beginTransaction and commit should be paired. If onNavigationItemSelected is called twice you run into trouble when the transaction is already committed.
Better use it this way:
if (id == R.id.contact) {
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
// Handle the camera action
transaction.replace(R.id.fragment, MyFirstFragment.newInstance());
transaction.commit();
}
Try this:
Use
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.my_list_fragment,container,false);
ListView listView= (ListView) view.findViewById(R.id.listView);
listView.setAdapter(new CustomAdapter(getActivity()));
return view;
}
The problems is that your listview is attached to Fragment and not to Activity.

Change layout in Navigation Drawer

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

recyclerview not loading adapter values in a fragment

I have a base navigation drawer activity, which will load a fragment. The fragment. The fragment has a recycler view in its layout. The recycler view has an adapter which use Glide to load images from internet. I'm not able to get the image loaded. (Have added the Internet permission in manifest).
My Base activity is:
import android.net.Uri;
import android.os.Bundle;
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.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Item1Fragment.OnFragmentInteractionListener {
/**
* Frame layout: Which is going to be used as parent layout for child activity layout.
* This layout is protected so that child activity can access this
*/
protected RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
relativeLayout = (RelativeLayout) findViewById(R.id.content_frame);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Add the Very First i.e Squad Fragment to the Container
Fragment item1Fragment = new Item1Fragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_frame, item1Fragment, null);
fragmentTransaction.commit();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#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.base, 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();
FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_camera) {
Fragment item1Fragment = new Item1Fragment();
fragmentTransaction.replace(R.id.content_frame, item1Fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
Fragment item2Fragment = new Item2Fragment();
fragmentTransaction.replace(R.id.content_frame, item2Fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
Toast.makeText(getApplicationContext(), "333", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_manage) {
Toast.makeText(getApplicationContext(), "444", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_share) {
Toast.makeText(getApplicationContext(), "555", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_send) {
Toast.makeText(getApplicationContext(), "666", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
}
Activity layout is:
<?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" android:background="#color/colorPrimary"
tools:openDrawer="start">
<RelativeLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include
layout="#layout/app_bar_base"
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_base"
app:menu="#menu/activity_base_drawer" />
</android.support.v4.widget.DrawerLayout>
Fragment:
import android.content.Context;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Item1Fragment extends Fragment {
private OnFragmentInteractionListener mListener;
private ArrayList<ImageModel> data = new ArrayList<>();
private GalleryAdapter mAdapter;
private RecyclerView mRecyclerView;
public static String IMGS[] = {
"https://images.unsplash.com/photo-1444090542259-0af8fa96557e?q=80&fm=jpg&w=1080&fit=max&s=4b703b77b42e067f949d14581f35019b",
"https://images.unsplash.com/photo-1439546743462-802cabef8e97?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1441155472722-d17942a2b76a?q=80&fm=jpg&w=1080&fit=max&s=80cb5dbcf01265bb81c5e8380e4f5cc1",
"https://images.unsplash.com/photo-1437651025703-2858c944e3eb?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1431538510849-b719825bf08b?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1434873740857-1bc5653afda8?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1439396087961-98bc12c21176?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1433616174899-f847df236857?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1438480478735-3234e63615bb?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1438027316524-6078d503224b?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
for (int i = 0; i < IMGS.length; i++) {
ImageModel imageModel = new ImageModel();
imageModel.setName("Image " + i);
imageModel.setUrl(IMGS[i]);
data.add(imageModel);
}
View view = inflater.inflate(R.layout.fragment_item1,container,false);
mRecyclerView = (RecyclerView)view.findViewById(R.id.list);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}else{
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
}
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(getActivity().getApplicationContext(), data);
mRecyclerView.setAdapter(mAdapter);
return view;
}
//
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
fragment layout:
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.akl.nav2.Item1Fragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/list" android:background="#FFBB00"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
Adapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.ArrayList;
import java.util.List;
/**
* Created by akl on 3/12/2016.
*/
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<ImageModel> data = new ArrayList<>();
public GalleryAdapter(Context context, List<ImageModel> data) {
this.context = context;
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200, 200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
public MyItemHolder(View itemView) {
super(itemView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.akl.nav2">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".BaseActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER"
android:theme="#style/AppTheme.NoActionBar" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
The code was fine. A clean build as suggested by #HoangNguyen was enough to make the code run.

Two Column RecyclerView inside scrollview

I want my 2 columns RecyclerView, i.e. using GridLayoutManager, inside scrollview. I found a way to put single column recyclerview inside scrollview from this link, but i cant figure out how to put Grid RecyclerView inside scrollview.
I found solution. Work perfect for me.
my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_grid_recycler_view"
tools:context="com.example.recyclerview_horizontal.GridRecyclerView">
<ScrollView
android:layout_width="match_parent"
android:fillViewport="true"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gridview inside scrollview"
android:layout_marginBottom="50dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="300dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gridview inside scrollview"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
MainActivity
package com.example.gridrecyclerviewscroll;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements RecyclerAdapter.DynamicHeight {
RecyclerView recyclerView;
RecyclerAdapter adapter;
ArrayList<Integer> list;
ArrayList<Integer> size;
TextView txt;
long sumHeight=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager lm = new GridLayoutManager(this,2);
// txt = (TextView) findViewById(R.id.txt1);
recyclerView.setLayoutManager(lm);
size = new ArrayList<>();
list = new ArrayList<>();
list.add(R.drawable.index1);
list.add(R.drawable.index2);
list.add(R.drawable.index3);
list.add(R.drawable.index4);
list.add(R.drawable.index5);
list.add(R.drawable.index6);
list.add(R.drawable.index8);
list.add(R.drawable.index9);
list.add(R.drawable.index10);
adapter = new RecyclerAdapter(list,this);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public void HeightChange(int position, int height) {
size.add(height);
sumHeight = calSum();
float density = this.getResources().getDisplayMetrics().density;
float viewHeight = sumHeight * density;
recyclerView.getLayoutParams().height = (int) sumHeight;
}
private long calSum() {
long tot=0;
for(int i=0;i<size.size();i++){
tot = tot + size.get(i);
}
return tot;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RecyclerViewAdapter
package com.example.gridrecyclerviewscroll;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nteam on 23/10/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Integer> list;
Context context;
private DynamicHeight dynamicHeight;
public RecyclerAdapter(ArrayList<Integer> list, DynamicHeight dynamicHeight){
this.list = list;
this.dynamicHeight = dynamicHeight;
}
public RecyclerAdapter(ArrayList<Integer> list){
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_card,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.img.setImageResource(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img;
public ViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img_thumbnail);
}
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position, List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
holder.itemView.post(new Runnable() {
#Override
public void run() {
int cellwidth = holder.itemView.getWidth();
int cellheight = holder.itemView.getHeight();
if(dynamicHeight!=null) dynamicHeight.HeightChange(position, cellheight);
}
});
}
public interface DynamicHeight {
void HeightChange(int position, int height);
}
}
All credits goes to #Ashkan

Categories

Resources