Android Replace Fragment in View Pager - android

I'm new to Android development and Java outside of simple JavaScripts for web pages. I've created a view pager that displays three different fragments. For the second fragment, BooksFragment, I use a grid view to display a grid of buttons that when the user presses should replace BooksFragment with another view.
The problem I run into is that although I'm using .replace() to replace the fragment, the second fragment just shows up on top of the original. Now, I've searched my problem extensively and I believe the reason that usually happens is when the original fragment is not created dynamically. Being the noob that I am, it does seem like I AM creating the fragments dynamically but I could be mistaken (I'm not using any tags in any of my XML files). Can anyone please help me out? My code is below:
MainActivity.java
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.app.FragmentManager;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
// strings for tabs
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// tab titles
private String[] tabs = {"Status",
"Schedule",
"Books"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.pager, new PlaceholderFragment()).commit();
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
TabsPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter{
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// First fragment activity
return new StatusFragment();
case 1:
// Second fragment activity
return new ScheduleFragment();
case 2:
// Third fragment activity
return new BooksFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
BooksFragment.java
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class BooksFragment extends Fragment implements OnClickListener {
// get database data
private static final String DB_NAME = "bookReadingTracker";
private static final String TABLE_NAME = "book_names";
private static final String BOOK_NAME_ID = "_id";
private static final String BOOKNAME = "bookname";
private static final String BOOKABBR = "bookabbr";
private SQLiteDatabase database;
private ArrayList<String> allbooksabbr;
private OnItemSelectedListener listener;
GridView gridView;
public static BooksFragment newInstance() {
BooksFragment f = new BooksFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(getActivity(), DB_NAME);
database = dbOpenHelper.openDataBase();
fillAllbooksabbr();
View view = inflater.inflate(R.layout.books_fragment, container, false);
gridView = (GridView) view.findViewById(R.id.gridviewBooks);
gridView.setAdapter(new MyAdapter(getActivity(), allbooksabbr));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
///////////////////
Fragment chapterDetailFragment = ChaptersFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.booksFragmentHolder, chapterDetailFragment).commit();
/////////////////////
}
});
return view;
}
private void fillAllbooksabbr() {
allbooksabbr = new ArrayList<String>();
Cursor allbooksabbrCursor = database.query(TABLE_NAME, new String[] {BOOK_NAME_ID, BOOKABBR},
null, null, null, null, "CAST (" + BOOK_NAME_ID + " AS INTEGER)");
allbooksabbrCursor.moveToFirst();
if(!allbooksabbrCursor.isAfterLast()) {
do {
String bookabbr_array = allbooksabbrCursor.getString(1);
allbooksabbr.add(bookabbr_array);
} while (allbooksabbrCursor.moveToNext());
}
allbooksabbrCursor.close();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
MyAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> allbooksabbr;
public MyAdapter(Context context, ArrayList<String> allbooksabbr) {
this.context = context;
this.allbooksabbr = allbooksabbr;
}
public View getView(int position, View convertView, ViewGroup parent) {
View gridView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.books_button, null);
} else {
gridView = (View) convertView;
}
//gridView = new View(context);
gridView.setBackgroundColor(0xff645C69);
TextView bookButton = (TextView) gridView.findViewById(R.id.bookbutton);
bookButton.setText(allbooksabbr.get(position));
return gridView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return allbooksabbr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
Here are my XML files:
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.gclapps.bookreadingscheduletracker.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
books_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/booksFragmentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textViewBooks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Books"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#666666"
android:paddingTop="10dp"
android:paddingBottom="5dp" />
<GridView
android:id="#+id/gridviewBooks"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="60dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="2dp"
android:horizontalSpacing="2dp" >
</GridView>
</FrameLayout>
Please help me find the reason why my BooksFragment view doesn't get replaced with my ChaptersFragment view. If the BooksFragment view is indeed not created dynamically, please help me do so. I've read the documentation on how to do it, but am not able to figure out how to do it in my case with using the viewpager. Thanks!

Ok so after a quick look through your code, I noticed you used getChildFragmentManager() here:
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
getChildFragmentManager() manages fragments that are children of the current fragment. So when you call replace() , it doesn't actually remove the displayed BookFragment since it is not a child of the current fragment (the current fragment IS the BookFragment).
So normally to replace the fragment, I'd call getSupportFragmentManager() to get the right manager, but since you're using a ViewPager it makes things more difficult. You'd probably need to somehow change the ViewPager adapter on gridview item click with a new adapter that returns ChapterDetailFragment in its getItem() method.
You might be able to do something like this:
public class TabsPagerAdapter extends FragmentPagerAdapter{
private boolean isChapterDetailShowing;
private int chapter;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// First fragment activity
return new StatusFragment();
case 1:
// Second fragment activity
return new ScheduleFragment();
case 2:
// Third fragment activity
if (isChapterDetailShowing)
return new ChapterDetailFragment();
else
return new BooksFragment();
}
return null;
}
public void showChapter(int chapter) {
this.chapter = chapter;
isChapterDetailShowing = true;
notifyDataSetChanged();
}
Then create a method in the Activity, which calls the showChapter() on the adapter. This method would be called in BookFragment's GridView onItemClickListener (use getActivity() and cast it to MainActivity).
Disclaimer: not 100% sure this will work

Related

Viewpager cannot change imageView background programmatically

I am trying to initialize a ViewPager. I've failed to set image of programmatically to the viewpager. This is what I've come up with:
TutorialActivity.class
package app.trial.com;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class TutorialActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 3;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TutorialFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
TutorialFragment.class
package app.trial.com;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class TutorialFragment extends Fragment {
public static final String ARG_PAGE = "page";
private int mPageNumber;
public static TutorialFragment create(int pageNumber) {
TutorialFragment fragment = new TutorialFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public TutorialFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPageNumber = getArguments().getInt(ARG_PAGE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_tutorial, container, false);
switch(mPageNumber) {
case 1:
((ImageView) rootView.findViewById(R.id.tutorialImage)).setImageResource(R.drawable.tutorial_03);
break;
case 2:
((ImageView) rootView.findViewById(R.id.tutorialImage)).setImageResource(R.drawable.tutorial_02);
break;
case 3:
((ImageView) rootView.findViewById(R.id.tutorialImage)).setImageResource(R.drawable.tutorial_03);
break;
default:
break;
}
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
When I try to change R.id.tutorialImage using rootView.findViewById(R.id.tutorialImage).setImageResource() it doesn't change the background image. Also, it doesn't return null.
By the way my fragmentTutorial layout is:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="app.trial.com.TutorialFragment">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tutorialImage" />
</ScrollView>
</FrameLayout>

Add view at end and start of view pager dynamically

Initially my ViewPager takes list and set view accordingly. But if the end of ViewPager or start of ViewPager is reached I want to add more view to ViewPager and set positions accordingly, how can I accomplish this by writing an efficient code?
This is my Adapter
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TouchImageView image;
ImageEntity entity=list.get(position);
final TextView text;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,false);
// Locate the TextViews in viewpager_item.xml
image = (TouchImageView) itemView.findViewById(R.id.imageView1);
View progress=itemView.findViewById(R.id.progress);
text=(TextView) itemView.findViewById(R.id.text);
text.setVisibility(View.INVISIBLE);
text.setText(entity.message);
makeTextViewResizable(text, 1, "View more", true);
// Capture position and set to the TextViews
image.setImageURI(Uri.parse(Constants.FLDR_IMG+entity.localImageName));
ContextCommons.loadMainImage(context, entity, progress, image);
// Add viewpager_item.xml to ViewPager
container.addView(itemView);
return itemView;
}`
This is custom ViewPager
public class CustomViewPager extends ViewPager{
float mStartDragX;
float x = 0;
OnSwipeOutListener mOnSwipeOutListener;
static final String TAG="CustomViewPager";
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setOnSwipeOutListener(OnSwipeOutListener listener) {
mOnSwipeOutListener = listener;
}
private void onSwipeOutAtStart() {
if (mOnSwipeOutListener!=null) {
mOnSwipeOutListener.onSwipeOutAtStart();
}
}
private void onSwipeOutAtEnd() {
if (mOnSwipeOutListener!=null) {
mOnSwipeOutListener.onSwipeOutAtEnd();
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch(ev.getAction() & MotionEventCompat.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
mStartDragX = ev.getX();
break;
}
return super.onInterceptTouchEvent(ev);
}
#Override
public boolean onTouchEvent(MotionEvent ev){
if(getCurrentItem()==0 || getCurrentItem()==getAdapter().getCount()-1){
final int action = ev.getAction();
float x = ev.getX();
switch(action & MotionEventCompat.ACTION_MASK){
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
if (getCurrentItem()==0 && x>mStartDragX) {
/here i want to update ArrayList from start which is supplied to view adapter/
ImageActivity.loadStart();
}
if (getCurrentItem()==getAdapter().getCount()-1 && x<mStartDragX){
//here i want to update Arraylist from bottom which is supplied to view adapter
ImageActivity.loadEnd();
}
break;
}
}else{
mStartDragX=0;
}
return super.onTouchEvent(ev);
}
public interface OnSwipeOutListener {
void onSwipeOutAtStart();
void onSwipeOutAtEnd();
}
}
So I need to update list which is supplied to ViewPager to add dynamic view when ViewPager reaches the end or start.
I am adding view like this which I think is a wrong approach
public static void loadStart(){
ArrayList<ImageEntity> image = null;
try {
ContextCommons.loadImages(context, Constants.DIRECTION_TOP, list.get(0).id);
image= SelectQueries.getTopLocalImagesOnId(context, list.get(0).id, Constants.DIRECTION_TOP);
list.addAll(0,image);
} catch (Exception e) {
e.printStackTrace();
}
viewPager.getAdapter().notifyDataSetChanged();
viewPager.setCurrentItem(image.size()-1);
}
I have made some editis to Googles viewPager example to keep it simple,
by clicking the button on fragment you can easily increase the pages to View Pager.
This is a demo I showed here how to notify anychanges as you wish to increase pages. you will have to make your own custom Adapter and list of pages to keep pages and it's position in check...
I am sorry, I would not be witting entire code :(
Make a fragment with following xml and code...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button" />
</LinearLayout>
and it's code is
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class MyFragment extends Fragment {
private Button button;
private TextView textView;
private static AddPage test;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_my, container, false);
button = (Button) layout.findViewById(R.id.button);
return layout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test.addAnotherPage();
}
});
}
public void setAddPage(AddPage addPage) {
test = addPage;
}
public interface AddPage {
void addAnotherPage();
}
}
Main Activity xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AddingPagesTest">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Activities Code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class AddingPagesTest extends AppCompatActivity {
public static int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private MyFragment set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_pages_test);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#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_adding_pages_test, menu);
return true;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter implements MyFragment.AddPage {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
MyFragment myFragment = new MyFragment();
myFragment.setAddPage(this);
return myFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public void addAnotherPage() {
NUM_PAGES++;
mPagerAdapter.notifyDataSetChanged();
}
}
}

GridView items are not selectable in Fragment

I have a Fragment in an Activity and I'm trying to display a GridView` from a custom adapter.I'm able to display the GridView but unable to select any item of the gridview.
Can any one help me in identifying the issue.
Please find the code I have used :
//MainActivity
package com.example.frag;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
GridView optionsGridView;
ArrayList<InfoItems> items = new ArrayList<InfoItems>();
OptionsAdapter adapter;
String items2[] = {"1","2","3","4"};
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
// implentation of display of options in GridView
optionsGridView = (GridView) rootView.findViewById(R.id.optionsGrid);
/*items.add(new InfoItems("Passport"));
items.add(new InfoItems("Aadhar"));
items.add(new InfoItems("Pan"));
items.add(new InfoItems("DL"));*/
adapter = new OptionsAdapter(this.getActivity(), items2);
optionsGridView.setAdapter(adapter);
return rootView;
}
}
}
Custom Adapter
package com.example.frag;
import java.util.ArrayList;
import dalvik.bytecode.OpcodeInfo;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class OptionsAdapter extends BaseAdapter{
private Context context;
private ArrayList<InfoItems> infoItems;
String items[];
public OptionsAdapter(Context context,ArrayList<InfoItems> items) {
// TODO Auto-generated constructor stub
this.context = context;
this.infoItems = items;
}
public OptionsAdapter(Context contsxt,String txt[]) {
// TODO Auto-generated constructor stub
this.context = contsxt;
this.items = txt;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return infoItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.info_options, null);
}
TextView option = (TextView) convertView.findViewById(R.id.optionsItem);
option.setText(items[position]);
return convertView;
}
}
fragment xml -- layout which will be displayed in the fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.frag.MainActivity$PlaceholderFragment" >
<GridView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/optionsGrid"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:numColumns="2"
android:gravity="center"
android:layout_marginTop="10dp"/>
</RelativeLayout>
item xml -- list item of the custom adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000"
android:clickable="true">
<TextView android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:gravity="center"
android:textColor="#f000ff"
android:textSize="20sp"
android:textStyle="bold"
android:id="#+id/optionsItem"
android:text="passport"
android:clickable="true"
android:layout_gravity="center"/>
</LinearLayout>
Squonk is correct, you need to call optionsGridView.setAdapter(new OnItemClickListener....). You could also implement OnItemClickListener in your fragment and call optionsGridView.setAdapter(this).
Inside your PlaceholderFragment put this like below :
optionsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//do your stuff!
}
});

Creating ListView with android.support.v4.view.ViewPager showing nothing

I'm trying to create a ListView that each cell can be shifted as ViewPager.
Similar to Google Gmail app, that can shift emails in order to delete the emails.
It is working BUT showing nothing.
I created a ListView with BaseAdapter.
The Adapter create ViewPager with PagerAdapter that implements FragmentStatePagerAdapter.
The PagerAdapter activate the Fragment that supposed to show the data at the cells in the pagers.
Can you please help?
package com.tegrity.gui;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MyFregment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* simple ListView
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_view1, container, false);
ListView mMyListView = (ListView) view.findViewById(R.id.myList1);
// create the my adapter
MyAdapter mMyAdapter = new MyAdapter(getActivity());
mMyListView.setAdapter(mMyAdapter);
// This is working but without the ListView
// view = inflater.inflate(R.layout.connect_pager_view, null);
// android.support.v4.view.ViewPager myPagerUnit =
// (android.support.v4.view.ViewPager)
// view.findViewById(R.id.connect_pager);
// PagerAdapter pagerAdapter = new MyPagerAdapter(getFragmentManager(),
// 0);
// myPagerUnit.setAdapter(pagerAdapter);
return view;
}
// the data
private static ArrayList<String> mMyList0 = new ArrayList<String>();
/**
* my adapter
*/
public class MyAdapter extends BaseAdapter {
// the data
private ArrayList<String> mMyList = new ArrayList<String>();
private Context mContext;
private LayoutInflater mInflater;
public MyAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMyList.add("First line");
mMyList.add("Second line");
mMyList.add("Third line");
mMyList0 = mMyList;
}
#Override
public int getCount() {
return mMyList.size();
}
#Override
public Object getItem(int position) {
return mMyList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// optimization
if (convertView == null) {
convertView = mInflater.inflate(R.layout.connect_pager_view,
null);
}
android.support.v4.view.ViewPager myPagerUnit = (android.support.v4.view.ViewPager) convertView
.findViewById(R.id.connect_pager);
PagerAdapter pagerAdapter = new MyPagerAdapter(
getFragmentManager(), position);
myPagerUnit.setAdapter(pagerAdapter);
myPagerUnit
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
((Activity) mContext).invalidateOptionsMenu();
}
});
return convertView;
}
}
/**
* A simple pager adapter
*/
class MyPagerAdapter extends FragmentStatePagerAdapter {
// parameters from the my adapter
private int mPosition;
public MyPagerAdapter(FragmentManager fm, int position) {
super(fm);
mPosition = position;
}
#Override
public Fragment getItem(int pagePosition) {
return MyUnitFragment.create(pagePosition, mPosition);
}
#Override
public int getCount() {
return 2; // pager of 2 cells
}
}
/**
* my basic unit
*/
public static class MyUnitFragment extends Fragment {
public static final String PAGE = "page";
public static final String POSITION = "position";
private int mPageNumber;
// parameter from the my adapter
private int mPosition;
/**
* Factory method for this fragment class. Constructs a new fragment for
* the given page number.
*/
public static MyUnitFragment create(int pageNumber, int position) {
MyUnitFragment fragment = new MyUnitFragment();
Bundle args = new Bundle();
args.putInt(PAGE, pageNumber);
args.putInt(POSITION, position);
fragment.setArguments(args);
return fragment;
}
public MyUnitFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(PAGE);
mPosition = getArguments().getInt(POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
View convertView = (View) inflater.inflate(R.layout.bookmark_unit,
container, false);
// page parts
String data = mMyList0.get(mPosition);
TextView textView = (TextView) convertView
.findViewById(R.id.bookmarkText1);
switch (mPageNumber) {
case 0: {
textView.setText(data + " at the first page");
break;
}
case 1: {
textView.setText(data + " at the second page");
break;
}
}
return convertView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
}
XML for the ListView myList1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/white" >
<ListView android:id="#+id/myList1"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:divider="#drawable/course_divider"
android:dividerHeight="2dp"
android:cacheColorHint="#00000000" >
</ListView>
</LinearLayout>
XML for the Pager connect_pager_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/connect_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</android.support.v4.view.ViewPager>
The list unit my_unit.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/myText1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#color/black"
android:layout_marginLeft="6dp">
</TextView>
</LinearLayout>
ViewPager in ListView is a bad idea.
You can use this Swipe-to-Dismiss library for deleting https://github.com/romannurik/android-swipetodismiss
You go through following link to implement gmail like delete from list function:
https://github.com/47deg/android-swipelistview

No view for id for fragment

I'm trying to use le lib SlidingMenu in my app but i'm having some problems.
I'm getting this error:
11-04 15:50:46.225: E/FragmentManager(21112): No view found for id
0x7f040009 (com.myapp:id/menu_frame) for fragment
SampleListFragment{413805f0 #0 id=0x7f040009}
BaseActivity.java
package com.myapp;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuItem;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class BaseActivity extends SlidingFragmentActivity {
private int mTitleRes;
protected ListFragment mFrag;
public BaseActivity(int titleRes) {
mTitleRes = titleRes;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(mTitleRes);
// set the Behind View
setBehindContentView(R.layout.menu_frame);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new SampleListFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
}
// customize the SlidingMenu
SlidingMenu slidingMenu = getSlidingMenu();
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);
slidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);
slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.setMenu(R.layout.slidingmenu);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.myapp.SampleListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</fragment>
menu_frame.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
SampleListFragment.java
package com.myapp;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class SampleListFragment extends ListFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SampleAdapter adapter = new SampleAdapter(getActivity());
for (int i = 0; i < 20; i++) {
adapter.add(new SampleItem("Sample List", android.R.drawable.ic_menu_search));
}
setListAdapter(adapter);
}
private class SampleItem {
public String tag;
public int iconRes;
public SampleItem(String tag, int iconRes) {
this.tag = tag;
this.iconRes = iconRes;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null);
}
ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon);
icon.setImageResource(getItem(position).iconRes);
TextView title = (TextView) convertView.findViewById(R.id.row_title);
title.setText(getItem(position).tag);
return convertView;
}
}
}
MainActivity.java
package com.myapp;
import java.util.ArrayList;
import beans.Tweet;
import database.DatabaseHelper;
import adapters.TweetListViewAdapter;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends BaseActivity {
public MainActivity(){
super(R.string.app_name);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listview = (ListView) findViewById(R.id.listview_tweets);
DatabaseHelper db = new DatabaseHelper(this);
ArrayList<Tweet> tweets = db.getAllTweets();
TweetListViewAdapter adapter = new TweetListViewAdapter(this, R.layout.listview_item_row, tweets);
listview.setAdapter(adapter);
setSlidingActionBarEnabled(false);
}
}
I don't understand why the view menu_frame is not found because I have a view with the id menu_frame and this view is a child of the layout menu_frame.
setBehindContentView() is used to set the layout of the SlidingMenu.
/**
* Set the behind view content to an explicit view.
* This view is placed directly into the behind view 's view hierarchy.
* It can itself be a complex view hierarchy.
*
* #param view The desired content to display.
* #param layoutParams Layout parameters for the view. (unused)
*/
public void setBehindContentView(View view, LayoutParams layoutParams) {
mViewBehind = view;
mSlidingMenu.setMenu(mViewBehind);
}
However, since in the BaseActivity you called slidingMenu.setMenu(R.layout.slidingmenu);, the menu layout will be overwritten to R.layout.slidingmenu. Hence, R.layout.menu_frame is not inflated and the ID cannot be found.
Try to remove either setBehindContentView() or setMenu().

Categories

Resources