I have to change the views on swipe. This can be obtained through view pager. But I have 60 views and creating 60 different fragment will not be a good approach.
Please someone guide me what will be the best way to design swiping 60 views.
Firstly create one fragment where you can inflate different views using "position" parameter as follow..
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
View mainView;
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) {
if(position==1){
mainview = inflater.inflate(R.layout.layout1, null);
}else if(position==2){
mainview =inflater.inflate(R.layout.layout2, null);
.
.
.
.
}else if(position==50){
mainview =inflater.inflate(R.layout.layout50, null);
}
return mainView;
}
}
Now in Your MainActivity Create an Adapter that extends FragmentPagerAdpater and in getItem() method create the instances of previously create fragment as follow
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Title1", "Title2"...., "Title50"};
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);
}
}
}
Then finally add this in your Activity's OnCreat() method...
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
yourViewPager.setAdapter(adapter);
Thus you will have to create single fragment and use it for multiple views.
Thank you. Hope it helps..!!
You can safely use the ViewPager with an implementation of FragmentStatePagerAdapter. The adapter will optimize the memory usage by destroying fragments that are not visible at a given moment. Check the documentation for details and code sample.
Below is the complete code to add Fragments to a View pager.
Since this is just a demonstration I have used just a textView and each fragment added will have a random colour.On clicking a button you can add as many fragments as you want.On clicking the Page you can just remove it from the View Pager.You can move from one Page to another in a View Pager by Swiping to the right or left.
MainActivity.java
import android.graphics.Color;
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.ViewPager;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends FragmentActivity {
private MyPagerAdapter mpg;
private ArrayList<MyFragment> fragmentlist = new ArrayList<>();
public FragmentManager fmr = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
mpg = new MyPagerAdapter(fmr,fragmentlist);
pager.setAdapter(mpg);
for (int q = 0; q < 5; q++) {
int r = new Random().nextInt(100) + 155;
int g = new Random().nextInt(100) + 155;
int b = new Random().nextInt(100) + 155;
fragmentlist.add(MyFragment.newInstance(q, "Page number: " + (q + 1), Color.rgb(r, g, b)));
mpg.notifyDataSetChanged();
}
Button B1 = (Button) findViewById(R.id.button);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int r = new Random().nextInt(100) + 155;
int g = new Random().nextInt(100) + 155;
int b = new Random().nextInt(100) + 155;
int count = mpg.getCount();
fragmentlist.add(MyFragment.newInstance(count, "Page number: " + (count+1), Color.rgb(r, g, b)));
mpg.notifyDataSetChanged();
}
});
}
public void delete(int pos) {
int i = 0;
while (i <= fragmentlist.size()) {
if (pos == fragmentlist.get(i).getPosition()) break;
i++;
}
fragmentlist.remove(i);
mpg.notifyDataSetChanged();
}
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<MyFragment> fragmentList;
public MyPagerAdapter(FragmentManager fm, ArrayList<MyFragment> f) {
super(fm);
this.fragmentList = f;
}
#Override
public Fragment getItem(int pos) {
return fragmentlist.get(pos);
}
#Override
public int getCount() {
return fragmentlist.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
MyFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.List;
public class MyFragment extends Fragment {
int pos;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.f_1, container, false);
pos = getArguments().getInt("num");
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("MainActivity", "Deleting at pos - " + pos);
MainActivity activity = (MainActivity) getActivity();
activity.delete(pos);
}
});
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
FrameLayout fl = (FrameLayout) v.findViewById(R.id.frame_layout);
tv.setText(getArguments().getString("msg"));
fl.setBackgroundColor(getArguments().getInt("colour"));
return v;
}
public int getPosition() {
return pos;
}
public static MyFragment newInstance(int num,String text,int clr) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putString("msg", text);
b.putInt("colour", clr);
b.putInt("num",num);
f.setArguments(b);
return f;
}
}
And the xml.files,
activity_main.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"
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.shakthivels.assingment10.MainActivity"
android:id="#+id/r_v"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD a fragment"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
f_1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/av"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/frame_layout">
<TextView
android:id="#+id/tvFragFirst"
android:layout_width="203dp"
android:layout_height="127dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26sp"
android:text="TextView"
android:layout_gravity="center"
android:textColor="#000000" />
</FrameLayout>
</RelativeLayout>
1
2
Related
I've created an about activity in my Android application, with a ViewPager. But I can't see any content
My AboutActivity.java:
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.loloof64.android.chess_positions_archiver.R;
/**
* The about activity
*/
public class AboutActivity extends Activity {
static final int NUM_ITEMS = 2;
AboutDialogFragmentPagerAdapter pagerAdapter;
ViewPager viewPager;
static String pagesContents [] = new String[NUM_ITEMS];
public void exit(View view){
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_dialog_layout);
pagesContents[0] = getString(R.string.this_app_manual);
pagesContents[1] = getString(R.string.about_resources_content);
pagerAdapter = new AboutDialogFragmentPagerAdapter(getFragmentManager(),
new String[]{
"Chess Positions Archiver",
getString(R.string.about_resources_title)
});
viewPager = (ViewPager) findViewById(R.id.about_dialog_pager);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
}
public static class AboutDialogFragmentPagerAdapter extends FragmentStatePagerAdapter {
private String [] titles;
public AboutDialogFragmentPagerAdapter(FragmentManager fragmentManager, String [] titles){
super(fragmentManager);
this.titles = titles;
}
#Override
public Fragment getItem(int position) {
return AboutDialogSingleFragment.newInstance(position);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
public static class AboutDialogSingleFragment extends Fragment {
static String PAGE_TEXT_KEY = "PageTextKey";
private String pageText;
static AboutDialogSingleFragment newInstance(int position){
AboutDialogSingleFragment fragment = new AboutDialogSingleFragment();
Bundle arguments = new Bundle();
arguments.putString(PAGE_TEXT_KEY, pagesContents[position]);
fragment.setArguments(arguments);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_dialog_single_page_layout, container, false);
TextView pageTextView = (TextView) view.findViewById(R.id.about_dialog_page_textview);
pageTextView.setText(pageText);
container.addView(view);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageText = getArguments() != null ? getArguments().getString(PAGE_TEXT_KEY) : getResources().getString(R.string.about_dialog_content_error);
}
}
}
My about_dialog_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/about_dialog_tabs"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/about_dialog_pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/quit_about"
android:onClick="exit" />
</RelativeLayout>
My about_dialog_single_page_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/about_dialog_page_textview"/>
</LinearLayout>
I am using the support library 13.
So, what is my programming error ?
android:layout_weight="1" works only with LinearLayout (it is a property of LinearLayout). Since the ViewPager's parent is a RelativeLayout the property is ignored, and your ViewPager has height 0, which explain why you are not see anything
I have an application page with viewpager containing two fragments.
When my activity pops up , a server request is made for loading current data and then adapter is set.
But the app crashes with the following error.
Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference
While debugging, viewPager.setAdapter(adapter) showed null pointer exception. Neither my viewPager is null nor my Adapter.
I am not able to figure out why this is happening.
Please help!!
Thanks in advance!!
Found the problem.. In my fragmentPagerAdapter, getItem() was returning null for a fragment.
Try this code
create a class file TabOne.java
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_one, null);
return rootView;
}
}
create a class file TabTwo.java
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_two, null);
return rootView;
}
}
**create xml file tab_one.xml and tab_two.xml **
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/tab_2" />
</RelativeLayout>
Create a class TabFragmentPageAdapter.java
package com.example.tabfragment;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Create a classs file TabFragments.java
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
public static final int TAB_LOGIN = 0;
public static final int TAB_REG = 1;
private TabHost tabHost;
private int currentTab = TAB_LOGIN;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
fragments = new ArrayList<Fragment>();
fragments.add(new TabOne());
fragments.add(new TabTwo());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1));
tabHost.addTab(newTab(R.string.tab_2));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
updateTab();
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case TAB_LOGIN:
TabOne login = (TabOne) fragments.get(currentTab);
break;
case TAB_REG:
TabTwo register = (TabTwo) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
Create you activity class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
public class MainActivity extends ActionBarActivity {
Fragment fragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new TabFragments();
Log.i("fragment", "" + fragment.getId());
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
}
}
Create mainactivity.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.DrawerLayout>
create tab fragment_home.xml file
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:background="#394c58"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
I am a relative newbie to android programming and I am having some issues. I'm am trying to attach fragments to a view pager for a todo application. I have 7 fragments that repersent each day. Each fragment loads correctly, but when I add a task, it shows across all fragments instead of only the one I entered the task in. Code is below. Any help would be great, thank you!
ViewPager Activity
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class ToDoActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
Parse.initialize(this, "uD7", "BrZkpvhY6Asi5oSq");
//ParseAnalytics.trackAppOpened(getIntent());
ParseObject.registerSubclass(Task.class);
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(ToDoListFragment.newInstance("Important And Urgent"));
fList.add(ToDoListFragment.newInstance("Important Not Urgent"));
fList.add(ToDoListFragment.newInstance("Not Important But Urgent"));
return fList;
}
private class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
}
FragmentActivity.java
public class ToDoListFragment extends Fragment implements AdapterView.OnItemClickListener {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
private EditText mTaskInput;
private ListView mListView;
private TaskAdapter mAdapter = null;
private Button mButton;
public static final ToDoListFragment newInstance(String message)
{
ToDoListFragment f = new ToDoListFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.important_urgent, container, false);
TextView messageTextView = (TextView)v.findViewById(R.id.textView);
messageTextView.setText(message);
mAdapter = new TaskAdapter(getActivity(), new ArrayList<Task>());
mTaskInput = (EditText) v.findViewById(R.id.task_input);
mListView = (ListView) v.findViewById(R.id.task_list);
mButton = (Button) v.findViewById(R.id.submit_button);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mTaskInput.getText().length() > 0){
Task t = new Task();
t.setACL(new ParseACL(ParseUser.getCurrentUser()));
t.setUser(ParseUser.getCurrentUser());
t.setDescription(mTaskInput.getText().toString());
t.setCompleted(false);
t.saveEventually();
mAdapter.insert(t, 0);
mTaskInput.setText("");
}
}
});
updateData();
return v;
}
public void updateData(){
ParseQuery<Task> query = ParseQuery.getQuery(Task.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Task>() {
#Override
public void done(List<Task> tasks, ParseException error) {
if(tasks != null){
mAdapter.clear();
for (int i = 0; i < tasks.size(); i++) {
mAdapter.add(tasks.get(i));
}
}
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Task task = mAdapter.getItem(position);
TextView taskDescription = (TextView) view.findViewById(R.id.task_description);
task.setCompleted(!task.isCompleted());
if(task.isCompleted()){
taskDescription.setPaintFlags(taskDescription.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}else{
taskDescription.setPaintFlags(taskDescription.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
task.saveEventually();
}
}
FragmentXML
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="Hello"
android:layout_gravity="center"
android:id="#+id/textView"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:background="#color/red"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/task_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="text"
android:hint="Enter a Task">
<requestFocus />
</EditText>
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
<ListView
android:id="#+id/task_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
If you are using the same fragment XML file for each fragment, then when you update one, you are going to update all of them. You would need to create 7 different XML layouts (they could be the same layout, but would need different identifiers), and update that fragment layout individually.
Fragments are basically individual activities, running in a single Activity. You can reuse Fragments in different Activities, but each Fragment should have it's own layout.
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
I am a beginner Android developer. I am trying to get my head around the ViewPager. Before I was trying to work with this example:
http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/
I had the views working, but could not get functionality working within that, and I was told that I need to use Fragments within the ViewPager.
I went with this tutorial instead:
http://tamsler.blogspot.co.uk/2011/11/android-viewpager-and-fragments-part-ii.html
I have got the basics of a ViewPager with a Fragment working:
FragmentPagerActivity.java
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class FragmentPagerActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 10;
private ViewPager mViewPager;
private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return PageFragment.newInstance("My Message " + index);
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
}
PageFragment.java:
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.TextView;
public class PageFragment extends Fragment {
public static PageFragment newInstance(String title) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
TextView textView = (TextView) view.findViewById(R.id.textView1);
textView.setText(getArguments().getString("title"));
return view;
}
}
main.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.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
I want to be able to replace the current layout within the ViewPager with 7 of my own layouts that already exist and add functionality to the layouts using Fragments. What can I do with the code that I already have and the changes to make to get this properly working?
If there are any examples of a ViewPager with Fragments available online as well rather than just going briefly over it like the do in the Adroid Developers blog, I will be very grateful.
Declare this inside your MyFragmentPagerAdapter:
private Fragment[] fragments = new Fragment[] { new Fragment1(),Fragment2(),Fragment3(),Fragment4(),Fragment5()};
then implement getItem method like this:
#Override
public Fragment getItem(int index) {
return fragments[index];
}
and for each fragment have it is own class and layout:
public class Fragment1 extends Fragment {
//your code here
}
Assuming you know how to create fragments themselves, just do something like this to get them into your view pager:
#Override
public Fragment getItem(int page) {
switch (page) {
case 0: return new MyFirstFragment();
case 1: return new MySecondFragment();
case 2: return new MyThirdFragment();
//and so on....
}
return null;
}
#Override
public int getCount() {
return [the count of total fragments];
}
instead of this:
#Override
public Fragment getItem(int index) {
return PageFragment.newInstance("My Message " + index);
}
I modified the answer from hambonious a bit:
Declare this inside your MyFragmentPagerAdapter :
private SparseArray<Fragment> fragments = new SparseArray<Fragment>();
then implement getItem method like this:
#Override
public Fragment getItem(int index) {
if(fragments != null && fragments.size() >= index)
return fragments.get(i);
else return null;
}
You also have to override getSize()
#Override
public int getCount() {
return fragments.size();
}
Then you can dynamic add and remove fragments from it.