I'm following a tutorial and trying to build in a grid view into my fragment and every time I launch the app it crashes. I opened up LogCat and it gives me nothing... Can someone help me find out what I can do to get this to display correctly and not crash the app? Thank you!!!
Below I've included my Main Activity, GridView Adapter and Fragment...
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private Char
Sequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set the first title
mTitle = "Inventory";
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
// Remove shadow under actionbar
getSupportActionBar().setElevation(0);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new Inventory_Fragment();
mTitle = getString(R.string.title_section1);
break;
case 1:
objFragment = new Orders_Fragment();
mTitle = getString(R.string.title_section2);
break;
case 2:
objFragment = new Cart_Fragment();
mTitle = getString(R.string.title_section3);
break;
case 3:
objFragment = new Settings_Fragment();
mTitle = getString(R.string.title_section4);
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.inventory_layout, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
// MARK: - Helpers
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
GridViewAdapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Created by kenbarlow on 5/20/15.
*/
public class GridViewAdapter extends BaseAdapter {
private Context context;
public GridViewAdapter(Context context) {
context = context;
}
private int[] icons = {
// Temporary
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
R.drawable.image11,
R.drawable.image12,
R.drawable.image13,
R.drawable.image14,
R.drawable.image15,
R.drawable.image16,
R.drawable.image17
};
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int position){
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(10, 10, 10, 10);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(icons[position]);
return imageView;
}
}
Inventory_Fragment --- I Feel like the problem is in here but I'm not sure.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
/**
* Created by kenbarlow on 5/19/15.
*/
public class Inventory_Fragment extends Fragment {
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.inventory_layout, container, false);
GridView gridview = (GridView) getActivity().findViewById(R.id.gridview);
gridview.setAdapter(new GridViewAdapter(this));
return rootView;
}
}
I guess your are trying to find a gridview in the activity's layout, which is wrong because the gridview is in the Fragment's layout.
Please change in your fragment code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.inventory_layout, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
if(gridview != null){
gridview.setAdapter(new GridViewAdapter(getActivity()));
}
return rootView;
}
If it's not the cause of the problem, please post a stacktrace when the crash happen (it should have already been done).
I have not looked at all the code yet. I reviewed GridViewAdapter and Inventory_Fragment.
Remove getItemId method in GridViewAdapter. You don't use it anyway. It is possible that the BaseAdapter is referencing it, and returning it null from that method may crash the adapter.
Code suggestion, return an item for this method:
#Override
public Object getItem(int position){
return icons[position];
}
LogCat and it gives me nothing...
if literally nothing, try to reset LogCat.
as i see in these lines
rootView = inflater.inflate(R.layout.inventory_layout, container, false);
GridView gridview = (GridView) getActivity().findViewById(R.id.gridview);
you are inflating and makeing rootView to find your inner layouts. so instead of getActivity() in second line use your rootView.
and remember to put your gridView layout inside inventory_layout
I am not sure if it is the only issue or not, but this one looks a bit wrong.
In your Inventory_Fragment class:
gridview.setAdapter(new GridViewAdapter(this));
You should change it to this:
gridview.setAdapter(new GridViewAdapter(getActivity()));
Also please upload your layouts and/or logcat report here. It is hard to go through the code like this.
Related
I have a ListView in my Fragment class. This ListView has three items, and every item in the ListView has two buttons, btn+ and btn-, and a TextView.
When I run the app and press the btn+ in the first item, I don't know why but the value of the TextView in the last item is incremented. When I click the btn-, again the value of the last TextView is decremented.
This is my adapter:
package com.example.lie_.tablayout;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import java.util.ArrayList;
/**
* Created by Ali on 17/08/2017.
*/
public class MenuListPizzaAdapter extends BaseAdapter {
View vv;
TextView txtOrderNUM;
int counter=0;
private ArrayList <BuyMenuListPizza> BuyMenuListPizza;
private Context C;
public MenuListPizzaAdapter(Context c, ArrayList<BuyMenuListPizza> BuyMenuListPizza) {
this.BuyMenuListPizza = BuyMenuListPizza;
this.C=c;
}
#Override
public int getCount() {
return BuyMenuListPizza.size();
}
#Override
public Object getItem(int i) {
return BuyMenuListPizza.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View View, ViewGroup parent)
{
if (View == null) {
View = LayoutInflater.from(C).inflate(R.layout.buy_menu_list_pizza, parent, false);
}
TextView txtitemname = (TextView)View.findViewById(R.id.txtitemname);
SimpleRatingBar ratingbar = (SimpleRatingBar)View.findViewById(R.id.ratingbar);
final TextView txtitemcontent = (TextView)View.findViewById(R.id.txtitemcontent);
ImageView btnOrderADD = (ImageView)View.findViewById(R.id.btnOrderADD);
ImageView btnOrderDEL = (ImageView)View.findViewById(R.id.btnOrderDEL);
ImageView imgitem = (ImageView)View.findViewById(R.id.imgitem);
txtitemname.setText(BuyMenuListPizza.get(position).getName());
ratingbar.setRating(BuyMenuListPizza.get(position).getRating());
txtitemcontent.setText(BuyMenuListPizza.get(position).getContents());
btnOrderADD.setImageResource(BuyMenuListPizza.get(position).getImgplus());
btnOrderDEL.setImageResource(BuyMenuListPizza.get(position).getImgminues());
imgitem.setImageResource(BuyMenuListPizza.get(position).getImgpizza());
Toast.makeText(parent.getContext(),"Position getView : " + position,Toast.LENGTH_LONG).show();
txtOrderNUM = (TextView)View.findViewById(R.id.txtOrderNUM);
txtOrderNUM.setText(BuyMenuListPizza.get(position).getCount() + "");
btnOrderADD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int coun= BuyMenuListPizza.get(position).getCount();
coun++;
txtOrderNUM.setText( coun+"");
}
});
btnOrderDEL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int coun= BuyMenuListPizza.get(position).getCount();
coun--;
if(coun<0){
}
else
txtOrderNUM.setText(coun+"");
}
});
return View;
}
}
This is my Fragment class :
public class Pizza extends Fragment {
TextView txtOrderNUM;
ArrayList<BuyMenuListPizza> arrayList;
ListView MenuPizzaList;
Context c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.pizza, container, false);
MenuPizzaList = ( ListView)android.findViewById(R.id.MenuPizzaList);
arrayList=BuyMenuListPizzaCollection.getBuyMenuListPizza();
MenuPizzaList.setAdapter(new MenuListPizzaAdapter(container.getContext(),arrayList));
// MenuPizzaList.setOnItemClickListener(new oncitemlicklistener());
return android;
}
Please don't say go to xml file and change attribute because I changed that and my code is running and OnClickListener is ok but it doesn't work correctly.
I have searched for more than several days and I didn't find anything.
i found problem solving use : notyficationitemselected(getadapterposition)
This is driving me crazy. I'm trying to switch fragments by using a spinner, but I can't figure out where my mistake is. When I click on one of the spinner items, it always shows me the content of fragment 3, the others will not appear.
I browsed through the internet for hours now, but couldn't find a understandable solution for my problem, since I'm new to android programming.
Thankful for any help!
MainActivity.java
// Setup spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new MyAdapter(
toolbar.getContext(),
new String[]{
"Fragment 1",
"Fragment 2",
"Fragment 3"
}));
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
switch (position) {
case 0:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment1.newInstance()).commit();
case 1:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment2.newInstance()).commit();
default:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment3.newInstance()).commit();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Fragment1.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1Fragment extends Fragment {
public static Fragment1Fragment newInstance() {
Fragment1Fragment fragment = new Fragment1Fragment();
return fragment;
}
public Fragment1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment1, container, false);
return rootView;
}
}
My dear,
switch (position) {
case 0:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment1.newInstance()).commit();
break;
case 1:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment2.newInstance()).commit();
break;
default:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Fragment3.newInstance()).commit();
break;
}
Without break statement your all 3 lines executed. So the 3rd Fragment.
I have been trying to Design an App That has PANEL like Google Drawers.
• MainActivity
package skynet.com.testnavigationpanel;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
Intent i=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("Falcon Shield", "We Protect Your Device!", BitmapFactory.decodeResource(getResources(), R.drawable.shieldavatar));
}
public void login_signup(View v)
{
switch(v.getId())
{
case R.id.log_in:
i=new Intent(this,Login.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
break;
case R.id.sign_up:
i=new Intent(this,Signup.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
// update the main content by replacing fragments
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSectionAttached(int anInt) {
}
}
•NavigationDrawerFragment
package skynet.com.testnavigationpanel;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List getMenu() {
List items= new ArrayList<>();
items.add(new NavigationItem(getString(R.string.homeFrag),getResources().getDrawable(R.drawable.ic_home)));
items.add(new NavigationItem(getString(R.string.loginFrag),getResources().getDrawable(R.drawable.ic_login)));
items.add(new NavigationItem(getString(R.string.signupFrag),getResources().getDrawable(R.drawable.ic_signup)));
items.add(new NavigationItem(getString(R.string.settingFrag),getResources().getDrawable(R.drawable.ic_setting )));
items.add(new NavigationItem(getString(R.string.shareFrag),getResources().getDrawable(R.drawable.ic_share )));
items.add(new NavigationItem(getString(R.string.aboutFrag),getResources().getDrawable(R.drawable.ic_about )));
return items;
}
public void showBackButton(){
if(getActivity()instanceof ActionBarActivity){
((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
* #param toolbar The Toolbar of the activity.
*/
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = (View) getActivity().findViewById(fragmentId).getParent();
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
Kindly Guide me in Mentioning the Right code into Below Method of MainActivity.
onNavigationDrawerItemSelect(int position)
{
//codes for fragments That i dont Know how to write
}
My Fragment Class(Please Check the Code if its Right or needs to be changed)
package skynet.com.testnavigationpanel;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Evan on 28-Dec-15.
*/
public class HomeFragment extends Fragment {
public static HomeFragment newInstance(){
HomeFragment fragment=new HomeFragment();
return fragment;
}
public HomeFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.activity_main,container,false);
return rootView;
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
((MainActivity)activity).onSectionAttached(1);
}
}
Same Goes with my Other fragments for login, signup, about, share, etc..with Relevant Changes in Layout id and Names.
Devs, Kindly Help ! Thanks
i wonder if someone can help me get it to work, i want to change the webview url every time i change a tab in the tabstrip
i am a new developer so any kind of help will be great.
the main code of the pager and tabs
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.astuetz.PagerSlidingTabStrip;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
#InjectView(R.id.toolbar)
Toolbar toolbar;
#InjectView(R.id.tabs)
PagerSlidingTabStrip tabs;
#InjectView(R.id.pager)
ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor;
private SystemBarTintManager mTintManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setSupportActionBar(toolbar);
// create our manager instance after the content view is set
mTintManager = new SystemBarTintManager(this);
// enable status bar tint
mTintManager.setStatusBarTintEnabled(true);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
pager.setCurrentItem(1);
changeColor(getResources().getColor(R.color.green));
tabs.setOnTabReselectedListener(new PagerSlidingTabStrip.OnTabReselectedListener() {
#Override
public void onTabReselected(int position) {
Toast.makeText(MainActivity.this, "Tab reselected: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment.newInstance().show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeColor(int newColor) {
tabs.setBackgroundColor(newColor);
mTintManager.setTintColor(newColor);
// change ActionBar color just if an ActionBar is available
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = new ColorDrawable(getResources().getColor(android.R.color.transparent));
LayerDrawable ld = new LayerDrawable(new Drawable[]{colorDrawable, bottomDrawable});
if (oldBackground == null) {
getSupportActionBar().setBackgroundDrawable(ld);
} else {
TransitionDrawable td = new TransitionDrawable(new Drawable[]{oldBackground, ld});
getSupportActionBar().setBackgroundDrawable(td);
td.startTransition(200);
}
oldBackground = ld;
currentColor = newColor;
}
public void onColorClicked(View v) {
int color = Color.parseColor(v.getTag().toString());
changeColor(color);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentColor", currentColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentColor = savedInstanceState.getInt("currentColor");
changeColor(currentColor);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
and the second code of the textview where i want to change it to webview.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
#InjectView(R.id.textView)
TextView textView;
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card,container,false);
ButterKnife.inject(this, rootView);
ViewCompat.setElevation(rootView,50);
textView.setText("CARD "+position);
return rootView;
}
}
that's all for now, the layouts files are less important, i will deal with it later.
You should setOnPageChangeListener and use webview.loadUrl(url1);
tabsStrip.setOnPageChangeListener(new OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
switch(position)
{
case 0:
webview.loadUrl(url1);
break;
case 1:
webview.loadUrl(url2);
break;
case 2:
webview.loadUrl(url3);
break;
}
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
I want to detect when a particular fragment of three fragments I have set up with a ViewPager comes on to screen. I have 3 fragments in the viewpager and have set up the viewpager with
mViewPager.setOffscreenPageLimit(2);
so all three fragments are constructed at once (since it stores 2 on each side). I checked that Fragment.onResume() is called just once and not when each fragment comes to the foreground. Is there another callback to ensure I can catch this event and send some analytics signal for it?
Thanks
You can use the ViewPager.setOnPageChangeListener() to set a ViewPager.OnPageChangeListener().
Use the listener for the selected page based on its position in the PagerAdapter.
Here's my sample app:
package net.ynotapps.testviewpagerfragment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
#InjectView(R.id.pager)
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
CustomPagerAdapter adapter = new CustomPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Put Code here //
// Example code //
if (position == 2) {
Toast.makeText(MainActivity.this, "Found Position 2 fragment", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static class CustomPagerAdapter extends FragmentPagerAdapter {
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
CustomFragment fragment = new CustomFragment();
Bundle bundle = new Bundle();
bundle.putString("display_text", String.format("Fragment %d is here.", position));
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 5;
}
}
public static class CustomFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
TextView tv = new TextView(getActivity());
tv.setText(getArguments().getString("display_text"));
return tv;
}
}
}
ViewPager source code:
// Dispatch the change to any listeners
if (mAdapterChangeListeners != null && !mAdapterChangeListeners.isEmpty()) {
for (int i = 0, count = mAdapterChangeListeners.size(); i < count; i++) {
mAdapterChangeListeners.get(i).onAdapterChanged(this, oldAdapter, adapter);
}
}
So, you can use the ViewPager.addOnAdapterChangeListener to listen the callback.