How to assign buttons on different spots of 70 images separately? - android

My Problem:
I have 70 images, and on each image I want to put transparent button
in such a way that when user taps on it, it plays a short audio
regarding the spot on image. Images are displaying in a ViewPager.
My Solution:
Now what I have in mind is I can create 70 fragments each containing respective image as background and I can assign button on each spot easily and assign actions to those buttons which will play their respective audio.
But
this doesn’t look like a good approach to include 70 fragments in a single app.
So how can I achieve this, and what would be a better approach I can use?

We can just have one fragment and create an ArrayList of Map(Button, RelatedAudioFile) data structure for holding buttons and related audio files. ArrayList index represents the page number.
Example:
Now lets say we have 3 viewPages. As most of the PagerAdapter index start from "0", let say Page-0 contains 3 buttons, Page-1 contains 1 button, Page-2 contains 2 buttons.
Pseudocode:
class PagerHolder extends Fragment {
//buttons list - here, arrayList index represents page number
//and at each index we have map of buttons (buttons in each of these pages) and the related audio files
private ArrayList<Map<Button, RelatedAudioFile>> pageButtonsList = new ArrayList<>();
//pager view
private ViewPager viewPager;
//pager adapter
private PagerAdapter pagerAdapter;
//current page number -- page in which we are in right now
private int currentpageNumber = 0;
//buttonListener -- one button listener for all the buttons in all the pages.
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
//here you can play the audio.
//buttonView -- is the same button-object that was pressed.
((RelatedAudioFile)pageButtonsList.get(currentpageNumber).get(buttonView)).play();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
//add buttons to the list
//page 0 buttons
HashMap<Button, RelatedAudioFile> page0Buttons = new HashMap<>();
page0Buttons.put(new Button(context), new RelatedAudioFile());
page0Buttons.put(new Button(context), new RelatedAudioFile());
page0Buttons.put(new Button(context), new RelatedAudioFile());
pageButtonsList.add(page0Buttons)
//Adding page 1 buttons:
HashMap<Button, RelatedAudioFile> page1Buttons = new HashMap<>();
page1Buttons.put(new Button(context), new RelatedAudioFile());
pageButtonsList.add(page1Buttons);
//Adding page 2 buttons:
HashMap<Button, RelatedAudioFile> page2Buttons = new HashMap<>();
page2Buttons.put(new Button(context), new RelatedAudioFile());
page2Buttons.put(new Button(context), new RelatedAudioFile());
pageButtonsList.add(page2Buttons);
for(Map<Button, RelatedAudioFile> pageButtons :pageButtonsList) {
for(Button button : pageButtons.keySet()) {
button.setOnClickListener(listener);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_editor_pager, container, false);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.setAdapter(pagerAdapter);
return v;
}
private class PagerAdapter extends FragmentPagerAdapter {
private ButtonFragment buttonFragment;
private PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pageNumber) {
currentpageNumber = pageNumber;
//pass the buttons to the fragment so that it can add these buttons to the screen
buttonFragment = ButtonFragment.newInstance(pageButtonsList.get(pageNumber).keySet());
//to add buttons on screen programatically at certain position you can refer here:
// http://stackoverflow.com/questions/3441475/android-change-absolute-position-of-a-view-programmatically
}
//number of pages
#Override
public int getCount() {
return 70;
}
}

You dont have to create 70 fragments. Instead, you could just use one ImageView as follows:
final List<Integer> list = new ArrayList<>();
list.add(R.drawable.img_0);
list.add(R.drawable.img_1);
...
list.add(R.drawable.img_69);
ImageView img = (ImageView)findViewById(R.id.imageView);
img.setBackgroundResource(list.get(yourIndex));
img.setOnClickListener(new OnClickListener());//plays the audio

You don't need to declare 70 fragments, just create one fragment and on that fragment declare global arrays of images and sound. Now when you redirect here at fragment just pass one integer variable in argument. So now you can display the image from array using that integer variable and on button click you can play audio from sound array using same integer number.

Use this custom view pager
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* Created by Jinesh on 06-01-2016.
*/
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
/*
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
*/
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Add this tag to your xml
<Your_package_name.CustomViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vP_asq_Pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
Then extend PagerAdapter
public class HomeAdapter extends PagerAdapter {
public HomeAdapter(){
}
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.adapter_surveyquestion_view, null);
/*do your operations on your views here
store the 70 images in arraylist and return the size of the arraylist in getCount() method of the adapter.show different images each time in
getView based on the position variable.*/
(container).addView(v);
return v;
}
#Override
public boolean isViewFromObject (View view, Object object){
return view == ((View) object);
}
#Override
public void restoreState (Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState () {
return null;
}
#Override
public void destroyItem (ViewGroup container,int position, Object object){
container.removeView((View) object);
}
}

This is how I would do. Pleas note that this is a single class solution for example purpose, you can separate classes
This will keep only 5 fragments at a time
Screen is divided into 4 buttons you can set alpha value of buttons and size as per need currently i kept it half transparent for example
I am using Glide for image loading to avoid OOM problem because of image loading
What it look like
The Solution :-
package com.example.sample;
import java.util.ArrayList;
import com.bumptech.glide.Glide;
import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class MainActivity extends FragmentActivity {
private static ArrayList<Integer> imageList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Load image data
for (int i = 0; i < 70; i++) {
imageList.add(R.drawable.ic_launcher);
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
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);
ViewPager viewPager = (ViewPager) rootView
.findViewById(R.id.image_pager);
// Limit number of pages that should be retained to either
// side of the current page
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(new SongDetailAdapter(getActivity()));
return rootView;
}
}
public static class SongDetailAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public SongDetailAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((FrameLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = mLayoutInflater.inflate(
R.layout.image_place_holder, container, false);
ImageView imageView = (ImageView) itemView
.findViewById(R.id.background);
itemView.findViewById(R.id.button1).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(1);
}
});
itemView.findViewById(R.id.button2).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(2);
}
});
itemView.findViewById(R.id.button3).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(3);
}
});
itemView.findViewById(R.id.button4).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(4);
}
});
Glide.with(mContext).load("").placeholder(imageList.get(position))
.crossFade(300).into(imageView);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((FrameLayout) object);
}
#Override
public Object instantiateItem(View arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
/*
* Play sound
*/
private void playSound(int buttonNumber) {
switch (buttonNumber) {
case 1: // play sound for Button1
case 2: // play sound for Button2
case 3: // play sound for Button3
case 4: // play sound for Button4
default: // play sound for Button n
// Playing default notification here for example
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager
.getRingtone(mContext, notification);
r.play();
break;
}
}
}
}
Layouts
Main Activity layout activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sample.MainActivity"
tools:ignore="MergeRootFrame" />
Main fragment layout 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.example.sample.MainActivity$PlaceholderFragment" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/image_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Image place holder with dummy buttons imae_place_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/white"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/holo_green_light"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/holo_blue_light"
android:text="Button" />
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/holo_red_light"
android:text="Button" />
</LinearLayout>
</LinearLayout>
</FrameLayout>

Related

GridView numColumns=auto_fit, prevent items from being stretched

I would like to display items in a dialog. I used GridView. If I don't set the column width manually, GridView used hard-coded column number 2 like figure 1. If I set the column width, then it showed as many columns as possible like figure 2.
The problem is GridView seems to stretch the item to fill the whole screen, when I set a hard-coded width for the item (refer the code below). What can I prevent this? My final destination is to remove the red area in Figure 2. That should shrink the dialogue width by the amount of the red areas.
Figure 1.
Figure 2.
my_dialogue.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Family"/>
<GridView
android:stretchMode="columnWidth"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:id="#+id/familyGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
my_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:background="#android:color/holo_red_dark"
android:layout_height="wrap_content">
<ImageView
android:background="#android:color/holo_blue_dark"
android:layout_width="48sp"
android:layout_height="48sp"/>
<TextView
tools:text="Some application"
android:id="#+id/tvLabel"
android:background="#android:color/holo_blue_bright"
android:gravity="center_vertical"
android:layout_width="192sp"
android:layout_height="48sp"/>
</LinearLayout>
MyDialogue.java
package com.example.me.test2;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
import static android.util.TypedValue.applyDimension;
public class MyDialogue extends AppCompatDialogFragment
{
String TAG = this.getClass().getName();
private static MyDialogue instance;
private GridView myGrid;
public static MyDialogue getInstance()
{
if(instance == null)
{
instance = new MyDialogue();
}
return instance;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
setStyle(STYLE_NO_TITLE, 0);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.my_dialogue, container, false);
myGrid = (GridView)v.findViewById(R.id.familyGrid);
//If I do not set the column width, it does not know the item width,
//and the column number falls back to 2.
Resources r = getResources();
float px = applyDimension(COMPLEX_UNIT_SP, 192+48, r.getDisplayMetrics());
myGrid.setColumnWidth((int)px);
ArrayList<String> list = new ArrayList<>();
list.add("Father: Homer Simpson");
list.add("Mother: Marge Simpson");
list.add("Son: Bart Simpson");
list.add("Daughter: Lisa Simpson");
list.add("Baby: Maggie Simpson");
list.add("Dog: Santa's L. Helper");
MyAdapter oa = new MyAdapter(list);
myGrid.setAdapter(oa);
return v;
}
class MyAdapter implements ListAdapter
{
List<String> list;
public MyAdapter(List<String> list)
{
this.list = list;
}
#Override
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer)
{
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer)
{
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = View.inflate(myGrid.getContext(), R.layout.my_item, null);
TextView tvLabel = (TextView) v.findViewById(R.id.tvLabel);
tvLabel.setText(list.get(position));
return v;
}
#Override
public int getItemViewType(int position)
{
return 0;
}
#Override
public int getViewTypeCount()
{
return 1;
}
#Override
public boolean isEmpty()
{
return list.isEmpty();
}
}
}
MainActivity.java
package com.example.me.test2;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnShow = (Button)findViewById(R.id.btnShow);
btnShow.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager manager = getSupportFragmentManager();
AppCompatDialogFragment dialogue = MyDialogue.getInstance();
dialogue.show(manager, "dialogue");
}
});
}
}
if i understood your question, you may want to put the gridView inside a linear layout, setting to grid view to fill the linear layout, but put some padding to the linear layout. good luck.

How to retain progress bar state while switching the fragments?

I have a navigation drawer where these many options are present
Image material
Video Material
Audio Material
We are maintaining separate fragment for each material and every fragment have grid view in which we are populating thumbnail of that material. Once user click on the thumbnail a full material will be downloaded(Using AsyncTask). I am displaying the progress bar over the thumbnail while downloading the full material.
Now here i stuck to a problem that suppose progress bar is showing 20% and i switched the fragment to another and again came back to the same and the downloading progress bar is lost.
I went to a solution to use intent service and broadcast receiver to populate the progress bar but in that case on every added bytes a broadcasting will be done is it a good practice ?
The previous answer wasn't good enough, I made up a new one, have a look, it works very well.
The code consists of the Base Class for fragments, Two fragments, Model for holding data for grid elements and Main UI thread.
The base class:
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Movsar Bekaev on 20/09/2015.
*/
public class GridFragment extends Fragment {
static ArrayList<xThumbnail> myInformation;
static Activity mActivity;
GAdapter adapter;
GridView grid;
enum fragment_names {FR1, FR2}
static fragment_names this_fragment_name;
public GridFragment() {
refresh();
}
protected void refresh() {
if (grid == null) {
grid = new GridView(mActivity);
grid.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
grid.setBackgroundColor(Color.WHITE);
grid.setNumColumns(2);
grid.setColumnWidth(GridView.AUTO_FIT);
grid.setVerticalSpacing(5);
grid.setHorizontalSpacing(5);
grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
}
adapter = new GAdapter(mActivity, myInformation);
grid.setAdapter(adapter);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
refresh();
return grid;
}
public class GAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<xThumbnail> mInfo;
// Gets the context so it can be used later
public GAdapter(Context c, ArrayList<xThumbnail> info) {
mInfo = info;
mContext = c;
}
// Total number of things contained within the adapter
public int getCount() {
return mInfo.size();
}
public xThumbnail getItem(int position) {
return mInfo.get(position);
}
// Require for structure, not really used in my code. Can
// be used to get the id of an item in the adapter for
// manual control.
public long getItemId(int position) {
return position;
}
public View getView(final int position,
View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.thumbnail, null);
final TextView tv = (TextView) v.findViewById(R.id.tvClickMe);
final ProgressBar pb = (ProgressBar) v.findViewById(R.id.prgb_progress);
pb.setProgress(mInfo.get(position).getProgress());
tv.setText(mInfo.get(position).getProgress() + "");
mInfo.get(position).setProgressBar(pb);
mInfo.get(position).setTextView(tv);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runOp(mInfo.get(position), position, this_fragment_name);
}
});
} else {
v = convertView;
}
return v;
}
}
private void runOp(final xThumbnail x, final int position, final fragment_names f_name) {
if (x.xt == null) {
x.xt = new Thread(new Runnable() {
#Override
public void run() {
for (int i = x.getProgress(); i <= 100; i++) {
// UNCOMMENT IF YOU WANT TO STOP THE PROCESS AFTER SWITCHING
// if ((f_name == this_fragment_name) && !mThread.isInterrupted()) {
final int progress = i;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
x.setProgressBar(adapter.getItem(position).getProgressBar());
x.setTextView(adapter.getItem(position).getTextView());
x.setProgress(progress);
x.getProgressBar().setProgress(progress);
x.getTextView().setText(progress + "");
// ARBITRARY CHANGE OF MYINFORMATION
// JUST TO SHOW THAT IT WORKS
if (progress == 20) {
myInformation.get(3).setProgress(12);
refresh();
}
// **********************************
}
});
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
// } else {
// return;
// }
}
}
});
}
if (!x.xt.isAlive())
x.xt.start();
}
}
The fr1.java:
public class fr1 extends GridFragment {
static ArrayList<xThumbnail> fr1Info;
public static fr1 newInstance(Activity act) {
mActivity = act;
return new fr1();
}
#Override
protected void refresh() {
if (fr1Info == null || fr1Info.size() == 0) {
fr1Info = new ArrayList<>();
for (int i = 0; i < 10; i++) {
xThumbnail x;
x = new xThumbnail();
fr1Info.add(x);
}
}
myInformation = fr1Info;
super.refresh();
}
}
The fr2.java:
public class fr2 extends GridFragment {
static ArrayList<xThumbnail> fr2Info;
public static fr2 newInstance(Activity act) {
mActivity = act;
return new fr2();
}
#Override
protected void refresh() {
if (fr2Info == null || fr2Info.size() == 0) {
fr2Info = new ArrayList<>();
for (int i = 0; i < 10; i++) {
xThumbnail x;
x = new xThumbnail();
fr2Info.add(x);
}
}
myInformation = fr2Info;
super.refresh();
}
}
The xThumbnail.java (model):
public class xThumbnail {
private int prgb_value = 0;
private ProgressBar pb;
private TextView tv;
public Thread xt;
public void setProgress(Integer i) {
prgb_value = i;
}
public Integer getProgress() {
return prgb_value;
}
public void setProgressBar(ProgressBar prb) {
pb = prb;
}
public ProgressBar getProgressBar() {
return pb;
}
public void setTextView(TextView tv) {
this.tv = tv;
}
public TextView getTextView() {
return tv;
}
}
The MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button btn_one, btn_two;
fr1 mFr1;
fr2 mFr2;
FragmentManager fm = getFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_one = (Button) findViewById(R.id.btn_one);
btn_two = (Button) findViewById(R.id.btn_two);
mFr1 = (fr1) fm.findFragmentByTag("fr1");
mFr2 = (fr2) fm.findFragmentByTag("fr2");
final FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frLayout);
btn_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GridFragment.this_fragment_name= GridFragment.fragment_names.FR1;
if (mFr1 == null) {
mFr1 = fr1.newInstance(MainActivity.this);
fm.beginTransaction().add(R.id.frLayout, mFr1, "fr1").commit();
} else {
fm.beginTransaction().detach(mFr1).commit();
fm.beginTransaction().attach(mFr1).commit();
}
}
});
btn_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GridFragment.this_fragment_name= GridFragment.fragment_names.FR2;
if (mFr2 == null) {
mFr2 = fr2.newInstance(MainActivity.this);
fm.beginTransaction().add(R.id.frLayout, mFr2, "fr2").commit();
} else{
fm.beginTransaction().detach(mFr2).commit();
fm.beginTransaction().attach(mFr2).commit();
}
}
});
}
}
activity_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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/btn_one"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="#+id/btn_two"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/prgb_uni"
android:layout_alignEnd="#+id/prgb_uni" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prgb_uni"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="#+id/frLayout"></FrameLayout>
</RelativeLayout>
thumbnail.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/prgb_progress" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="ClickMe!"
android:id="#+id/tvClickMe"
android:layout_gravity="center_horizontal"
android:textIsSelectable="false" />
</FrameLayout>
What it does:
We have here one base class, it operates with representation of views and populating progress bars.
It has field to work with current items (that holds progress bar values), every time when we switching between fragments this field is updated to respective values of Fragment1 or Fragment2, those fragments have static fields to hold their own data so it can be changed and used.
The thing with Thread and some other code is just to show that it's works and for better understanding.
I hope it will help.
PoC - https://youtu.be/uKGeX40z_mA :)
As an abstract blueprint you could add a download Service to your app and let it to download your materials.
For communicating with this service you might want to declare it as a bind-able service so that whenever user switch to that fragment your activity can bind to this service and see what is going on.
Using this way, you can report download progress to user and also you no longer need sending broadcasts.

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();
}
}
}

setCurrentItem call on ViewPager causes app to crash with outofmemory error

I am trying to create an app that has a bunch of low res images (each image around 50 - 70 KB). One could swipe through the image library, or based on certain buttons, go to specific image in the library. I used the ViewPager using the FragmentStatePagerAdapter (FSPA) as I understand that this is the most memory optimal way for swiping through images. I am expecting that this approach ensures that only 3 images/fragments are alive at any given point in time, hence there shouldn't be a memory issue as such. This approach works fine on most emulators. However, when I try with Nexus One emulator (I am using Android Studio), I see an issue. The swiping part works fine, but if I use a button to go to a specific page (using viewPager.SetCurrentItem() method), the app crashes with outofmemory error. What do I need to do to get this working (going to a particular image on click of a button)?
I have a main activity page, and two fragment pages. Here is the code:
Main activity page:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.tryslider.tryslider.MainActivity">
</RelativeLayout>
fragment pager (with the ViewPager and button):
<?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:gravity="center_horizontal"
android:orientation="vertical"
android:background="#5b9bd5"
android:padding="4dip" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/goButtonLabel"
android:id="#id/goButton"
android:textColor="#ffffff"
android:background="#drawable/abc_ab_transparent_dark_holo" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
fragment that contains the image:
<?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">
<ImageView
android:id="#id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:src="#drawable/first" />
</RelativeLayout>
This is my main activity code (notice the number in SetCurrentItem - I just move to an arbitrary image in the stack, say 5th image in this case (out of a total of 10 images):
package com.example.tryslider.tryslider;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import java.text.SimpleDateFormat;
public class MainActivity extends ActionBarActivity {
static final int ITEMS = 10;
MyAdapter viewAdapter;
ViewPager viewPager;
private Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
viewAdapter = new MyAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(viewAdapter);
goButton = (Button) findViewById(R.id.goButton);
goButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
viewPager.setCurrentItem(5, false);
}
});
}
#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 MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
return ImageFragment.init(position);
}
#Override
public void destroyItem(View collection, int position, Object o) {
super.destroyItem(collection, position, o);
View view = (View)o;
((ViewPager) collection).removeView(view);
view = null;
}
}
}
And the image fragment code:
package com.example.tryslider.tryslider;
/**
* Created by rahul on 8/3/14.
*/
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.AdapterView;
import android.widget.ImageView;
public class ImageFragment extends Fragment {
private int index;
private int[] mImages = new int[] {
R.drawable.first,
R.drawable.second,
R.drawable.third,
R.drawable.fourth,
R.drawable.fifth,
R.drawable.sixth,
R.drawable.seventh,
R.drawable.eighth,
R.drawable.ninth,
R.drawable.tenth
};
static ImageFragment init(int val) {
ImageFragment myFrag = new ImageFragment();
Bundle args = new Bundle();
args.putInt("val", val);
myFrag.setArguments(args);
return myFrag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
index = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_image, container,
false);
ImageView imageView = (ImageView) layoutView.findViewById(R.id.imageView);
imageView.setImageResource(mImages[index]);
return layoutView;
}
}
I tried going through many suggestions on SO and otherwise, but am struggling with this at the moment. Any help is greatly appreciated.
#Override
public void destroyItem(View collection, int position, Object o) {
super.destroyItem(collection, position, o);
View view = (View)o;
((ViewPager) collection).removeView(view);
view = null;
}
This section is not needed. The FragmentStatePager will handle destroying and recreating views.

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

Categories

Resources