Android - How to manage position of viewpager in adapter? - android

I am developing an android app, in it i am displaying a ListView with a number of items. on Click of an item i am passing item name and ArrayList of all items .
Intent myIntent = new Intent(context, DetailActivity.class);
myIntent.putExtra("name", name);
myIntent.putStringArrayListExtra("arraylistofitems", arraylistofitems);
context.startActivity(myIntent);
In DetailActivity, i want to show the clicked items from list and on scroll left or right show the remaining item from the list. I am using following code -
Intent mIntent = getIntent();
name = mIntent.getStringExtra("name");
names = mIntent.getStringArrayListExtra("arraylistofitems");
viewPager = (ViewPager) findViewById(R.id.idofviewpager);
adapter = new ViewPagerAdapter(context, arraylistofitems);
viewPager.setAdapter(adapter);
and ViewPagerAdapter looks like following -
public ViewPagerAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data=data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((MyLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// item views declaration
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item_id, container,
false);
//layout item initialization
((ViewPager) container).addView(itemView);
ParseQuery<ParseObject> query = ParseQuery.getQuery("myclass");
query.whereEqualTo("colName", data.get(position));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> itemList, ParseException arg1) {
for (int i = 0; i < itemList.size(); i++) {
ParseObject po = itemList.get(i);
//set the values from parse into views
}
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((MyLayout) object);
}
But all data being shown from starting (0th Position to length of arraylist).
Question - How do i implement scroll effect with clicked item being opened and on scrolling left left items should be display or vice-versa?

You can do one thing , pass position of item which is being clicked and get it on your detail activity same as you are getting item name and array of list. and then call following line -
viewPager.setCurrentItem(position);
So, now there is no need to manage position on adapter. adapter will take care of it.

Related

How to show loading image with progress bar and image also want to counting number in my gridview andriod studio

I have created android app like gallery which have some images using gridview fragment.
Functionality of my application is working fine and image showing in fragment gridview and also my second activity open when i click on item but i want to show loading image with progress bar when my image not load or take time for loading complete.
Also i want to show image counting number in gridview.
But i want to progress bar on loading images like this : WANT LINK THIS SCREENSHOT
My gridview looks like this : My gridview looks like this
already to find the
Here is my application fragment code :
public class CallFragment extends Fragment {
GridView grid;
String[] plan = {
"Student Bundle",
"SMS Plus Bundle",
"Instagram",
"Facebook",
"Flickr"
} ;
String[] web = {
"*3000",
"*106*1",
"Instagram",
"Facebook",
"Flickr"
} ;
int[] imageId = {
R.drawable.calla,
R.drawable.smsb,
R.drawable.person7,
R.drawable.person7,
R.drawable.person7
};
int[] fullimg = {
R.drawable.callaa,
R.drawable.smsbb,
R.drawable.person7,
R.drawable.person7,
R.drawable.person7
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_call,container,false);
CustomGrid adapter = new CustomGrid(getActivity(), plan, web, imageId, fullimg);
grid=(GridView) view.findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String value=(String)grid.getItemAtPosition(i);
Intent intent=new Intent(getActivity(),Book.class);
intent.putExtra("web", web[i]);
intent.putExtra("plan", plan[i]);
intent.putExtra("imageId", imageId[i]);
intent.putExtra("fullimg", fullimg[i]);
startActivity(intent);
}
});
return view;
}
Here is my application CustomAdapter code :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<String> personNames;
ArrayList<String> personCode;
ArrayList<Integer> personImages;
ArrayList<Integer> personImages1;
Context context;
public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> personCode, ArrayList<Integer> personImages, ArrayList<Integer> personImages1) {
this.context = context;
this.personCode = personCode;
this.personNames = personNames;
this.personImages = personImages;
this.personImages1 = personImages1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// set the data in items
//holder.name.setText(personNames.get(position));
holder.image.setImageResource(personImages.get(position));
//holder.image.setImageResource(personImages1.get(position));
// implement setOnClickListener event on item view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open another activity on item click
Intent intent = new Intent(context, SecondActivity.class);
//intent.putExtra("image", personImages.get(position)); // put image data in Intent
intent.putExtra("name", personNames.get(position)); // put image data in Intent
intent.putExtra("code", personCode.get(position)); // put image data in Intent
intent.putExtra("image", personImages1.get(position)); // put image data in Intent
context.startActivity(intent); // start Intent
}
});
}
#Override
public int getItemCount() {
return personNames.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// init the item view's
TextView name;
TextView code;
ImageView image;
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name = (TextView) itemView.findViewById(R.id.name);
code = (TextView) itemView.findViewById(R.id.code);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
}
Also if it is easier default image in place of loading images instead of progress bar will be fine.
Please provide me solution to implement this.
i hope you get my main point which i want and Thanks for help.

Viewpager not getting last item

I am using two Viewpager in my app,
1) First Viewpager displays images only
2) I am displaying price
now the issue is i have 4 images displaying in my viewpager1, and in second pager i have price as per selected product. first time it does not show anything, but when i scroll image and goes to next, it shows price..
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Picasso.with(ProductLandingActivity.this) .load(categorylist.get(position).getProductLanding_packLink())
.error(R.drawable.nopreview )
.placeholder(R.drawable.progress_animation)
.into(selectedImage);
System.out.println("Selected is"+position);
selectedname.setText(categorylist.get(position).getProductLanding_packDesc());
for (int i = 0; i < categorylist.get(position).getItems().size(); i++) {
System.out.println("ProductPack_ID : " + categorylist.get(position).getItems().get(i).getPackSize_sellingPrice());
}
temp = categorylist.get(position).getItems();
packadapter = new MyPacksPagerAdapter(ProductLandingActivity.this,categorylist);
pagerpacks.setAdapter(packadapter);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
adapter
private class MyPacksPagerAdapter extends PagerAdapter {
Context context;
ArrayList<PackListModel> packsizedata ;
public MyPacksPagerAdapter(Context context,ArrayList<PackListModel> packsizedata) {
this.context = context;
this.packsizedata = packsizedata;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
final OneActor oneActor;
View view;
LayoutInflater infl = ((Activity)context).getLayoutInflater();
view = infl.inflate(R.layout.list_item_pagerpacktitles, container,false);
oneActor = new OneActor();
// oneActor.avatar = (ImageView) view.findViewById(R.id.image);
oneActor.name = (TextView) view.findViewById(R.id.product_landing_packsname);
oneActor.cmtCount = (TextView) view.findViewById(R.id.product_landing_packsprice);
view.setTag(oneActor);
oneActor.name.setText(temp.get(position).getPackSize_packSize());
oneActor.cmtCount.setText(temp.get(position).getPackSize_sellingPrice());
((ViewGroup) container).addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return packsizedata.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
class OneActor{
// ImageView avatar;
TextView name,cmtCount;
}
}
By defaulat when i run the app it shows like this,in second pager it is not showing product price,
But when i scroll image it shows price
My Expected output is
This is my json response
http://pastebin.com/fbJang2B
First, as mentioned by #NotobharatKumar, you're loading the second adapter on a wrong event of the parent adapter, ie in onPageScrolled method. Second, you're setting a new adapter each time on that specific event, it seems useless. Finally, you are setting datas in an event, (I'm not sure why you're doing this but) I'd prefer to set it in a separate adapter and let the events listener for specific behaviors.
For me, it seems that you have two separate adapters, but one datas list shared by both. Assuming that, you have to set them both at start with their datas respectly, and on the event onPageSelected of the top adapter, you just have to automatically scroll the second. And if they have the same position in the list, onPageSelected should do the work correctly.
So, these modifications should solve your issue:
Your code in onScrollChanged, when you set the image and the text, seems really weird to me. I'd use a first adapter where I'll set all the datas like these two for the first ViewPager:
#Override
public void onCreate(Bundle savedInstansteState) {
...
// set a simple adapter for the first ViewPager
FirstPagerAdapter imageadapter =
new FirstPagerAdapter(ProductLandingActivity.this, categorylist);
pagerimages.setAdapter(imageadapter);
...
}
Then, as usual, set your datas in the FirstPagerAdapter:
#Override
public View getView(int position, View view, ViewGroup container) {
...
// set the content
Picasso.with(ProductLandingActivity.this)
.load(categorylist.get(position).getProductLanding_packLink())
.error(R.drawable.nopreview )
.placeholder(R.drawable.progress_animation)
.into(selectedImage);
selectedname.setText(
categorylist.get(position).getProductLanding_packDesc());
...
}
Then no need to (re)load the image or the text when an event is triggered, since they will be holding by the adapter.
You only use getPackSize_packSize() and getPackSize_sellingPrice() in the second adapter, so you should create a separate list to only fill with these datas but outside the swiping event. Start by initializing the second list and the adapters:
// get the Items to fill the pack items list (like you did for `temp`)
ArrayList<Items> packItems = new ArrayList<>();
for (int i = 0; i < categorylist.size(); i++) {
packItems.add(categorylist.get(position).getItems());
}
// fill the first adapter with your list of products (ie categorylist)
...
pagerimages.setAdapter(imageadapter);
...
// fill the second adapter with the pack items list
packadapter = new MyPacksPagerAdapter(ProductLandingActivity.this, packItems);
pagerpacks.setAdapter(packadapter);
You have to do this when categorylist is created and populated. So place this above code for example in your callback, when you retrieve the datas from your server.
Since the second list packItems is filling in the same order than categorylist, there will be no weird behavior by changing the both positions.
Now, in the second adapter, it's preferable to use the local list packsizedata, as follows:
#Override
public Object instantiateItem(ViewGroup container, int position) {
...
oneActor.name.setText(
packsizedata.get(position).getPackSize_packSize());
oneActor.cmtCount.setText(
packsizedata.get(position).getPackSize_sellingPrice());
...
}
Finally, control the bottom ViewPager by using onPageSelected event of the first:
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) { }
#Override
public void onPageSelected(int position) {
// set the second current page regarding the position of the first
pagerpacks.setCurrentItem(position);
}
#Override
public void onPageScrollStateChanged(int state) { }
});
Hope this will be helpful.
You should implement code for action at onPageSelected method because after page changed of your ViewPager then onPageSelected will be called.

How to get tab name

I am using slidingtablayout. There are 5 tabs and i am populating each of them with listview from different json requests. I need to get the name or the id of the tab on clicking on one of the items of the list view
You are going to need to supply us with your current code or implementation - that will give us some direction on how to help you.
But my first guess on your implementation: I am assuming when you say SlidingTabLayout you are referring to the code outlined on android developers: https://developer.android.com/samples/SlidingTabsBasic/src/com.example.android.common/view/SlidingTabLayout.html#l199
If that is the case, you can get the tab name from the view pager when a tab is clicked and registered in the click listener:
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
//Get tab name from mViewPager - differs based on your implementation
return;
}
}
}
}
Yes is that one outlined in the android developers
Ok, here is the situation
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view=null;
if(position == 0){
view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,container, false);
homeList = (ListView) view.findViewById(R.id.home_list);
queryImp(view, "");
homeJSONAdapter = new JSONAdapter(getActivity(), getActivity().getLayoutInflater());
homeList.setAdapter(homeJSONAdapter);
homeList.setOnItemClickListener(this);
}else{
view = getActivity().getLayoutInflater().inflate(R.layout.other_pager_item,container, false);
otherList = (ListView) view.findViewById(R.id.other_list);
queryImp(view, "other");
otherJSONAdapter = new JSONAdapterOther(getActivity(), getActivity().getLayoutInflater());
otherList.setAdapter(ekonomiaJSONAdapter);
otherList.setOnItemClickListener(this);
}
container.addView(view);
view.findViewById(R.id.item_title);
return view;
}
this is the code that populates the tabs on SlidingTabsBasicFragment and the following is the onclick for the items of the lists
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0)
{
JSONObject jsonObject = (JSONObject) homeJSONAdapter.getItem(position);
String imageURL = jsonObject.optString("img_url");
String artText = jsonObject.optJSONObject("content").optString("rendered");
String artTitle = jsonObject.optJSONObject("title").optString("rendered");
Intent detailIntent = new Intent(getActivity(), SingleArticle.class);
detailIntent.putExtra("imgURL", imageURL);
detailIntent.putExtra("articleText", artText);
detailIntent.putExtra("articleTitle", artTitle);
startActivity(detailIntent);
}else{
JSONObject jsonObject1 = (JSONObject) otherJSONAdapter.getItem(position);
String imageURL1 = jsonObject1.optString("img_url");
String artText1 = jsonObject1.optJSONObject("content").optString("rendered");
String artTitle1 = jsonObject1.optJSONObject("title").optString("rendered");
y
Intent detailIntent1 = new Intent(getActivity(), SingleArticleOther.class);
detailIntent1.putExtra("imgURL1", imageURL1);
detailIntent1.putExtra("articleText1", artText1);
detailIntent1.putExtra("articleTitle1", artTitle1);
startActivity(detailIntent1);
}
which basically, all it does is click on the item of the list and gets to the full article to read. For some reason it all gets a mess. (when i do a log on the position, it gets the position of the item of the list and not that of the tab) When i try to click on an item of the homeJsonAdapter it goes to the article of the otherJsonAdapter. I dont know why.
So what i want to do is get the name of the tab in which the listview is and based on that name, create the JsonAdapter and get the article

Filtered list item opens the original list items' activity

After a tremendous amount of time searching in here, and everywhere else I am hopeless to find a solution.
So here is my problem.
I have created a list-view and on top of that I added a search-bar.
When I use the search-bar, to filter the results... when I click on item 7, instead of opening the specific clicked activity i.e. 7, it always starts from the first one.
I am looking forward to your help guys; because I need it!
public class Group extends ListActivity {
// ArrayList thats going to hold the search results
ArrayList<HashMap<String, Object>> searchResults;
// ArrayList that will hold the original Data
ArrayList<HashMap<String, Object>> originalValues;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grouplist);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// these arrays are just the data that
// I'll be using to populate the ArrayList
String names[] = {/*list of names*/ };
String teams[] = {/*list of teams*/};
Integer[] photos = {R.drawable.... /*list of drawables*/};
Integer[] id ={/*Position*/};
originalValues = new ArrayList<HashMap<String, Object>>();
// temporary HashMap for populating the Items in the ListView
HashMap<String, Object> temp;
// total number of rows in the ListView
int noOfPlayers = names.length;
// now populate the ArrayList players
for (int i = 0; i < noOfPlayers; i++) {
temp = new HashMap<String, Object>();
temp.put("name", names[i]);
temp.put("team", teams[i]);
temp.put("photo", photos[i]);
temp.put("id", id[i]);
// add the row to the ArrayList
originalValues.add(temp);
}
// searchResults=OriginalValues initially
searchResults = new ArrayList<HashMap<String, Object>>(originalValues);
final CustomAdapter adapter = new CustomAdapter(this, R.layout.players, searchResults);
// finally,set the adapter to the default ListView
playersListView.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
// clear the initial data set
searchResults.clear();
for (int i = 0; i < originalValues.size(); i++) {
String playerName = originalValues.get(i).get("name").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
searchResults.add(originalValues.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
// listening to single list item on click
playersListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos=Integer.ParseInt(searchResults.get(position).get("id").toString());
switch (pos) {
case 0:
Intent newActivity = new Intent(TeamsList.this, Barca.class);
startActivity(newActivity);
break;
case 1:
etc...
}
}
}
});
}
Custom adapter Class:
private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>> {
public CustomAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
// let android do the initializing :)
super(context, textViewResourceId, Strings);
}
// class for caching the views in a row
private class ViewHolder {
ImageView photo;
TextView name, team;
}
ViewHolder viewHolder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.players, null);
viewHolder = new ViewHolder();
// cache the views
viewHolder.photo = (ImageView) convertView.findViewById(R.id.photo);
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.team = (TextView) convertView.findViewById(R.id.team);
//Take one textview in listview design named id
viewHolder.id = (TextView) convertView.findViewById(R.id.id);
// link the cached views to the convert view
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
int photoId = (Integer) searchResults.get(position).get("photo");
// set the data to be displayed
viewHolder.photo.setImageDrawable(getResources().getDrawable(photoId));
viewHolder.name.setText(searchResults.get(position).get("name").toString());
viewHolder.team.setText(searchResults.get(position).get("team").toString());
viewHolder.id.setText(searchResults.get(position).get("id").toString());
// return the view to be displayed
return convertView;
}
}
}
I think you cant find correct position on listview item click. so u can use one textview with visibility="Gone" and insert the position in that textview in every row. now u can easily access position while clicking on item with the value of textview which shows perfect position. Hope it works. Thanx
The problem is that Adapter is populated once but with search results it gets overViewed by the searched items so on clicking it refers to the original items of list instead of the filtered list once , so we have to use the filtered lists' positions instead of the original one, i also faced this problem, try this:
In your listView.setOnItemClickListener
playersListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//Object objFilteredItem = parent.getItemAtPosition(position);
//String a = searchResults.get(position);
switch (Integer.parseInt((String) adapter.getItem(position))) {
case 0:..
Intent newActivity = new Intent(TeamsList.this,Barca.class);
startActivity(newActivity);
break;
case 1:
etc...
break;
}
}
});
As from my previously answered question here, you have to override the getItem(position) method in your CustomAdapter. You are setting the onItemClick somewhat correctly but the list adapter doesn't know what exactly it's getting from getItem(position).
EDIT (details): You need to add something like this in your custom adapter -
#Override
public Object getItem(int position) {
return list.get(position);
}
You should already have the list in your custom adapter. If not, you can add a list reference to your CustomAdapter:
private ArrayList<HashMap<String, Object>> list;
Then setting it using a setter in your Group activity:
customAdapter.setList(searchResults);

Swipe Details View

I have ListView with items. I'm using XML to parse data. In that moment I parse data for one item in DetailsView. When I clicked on item, how to make DetailsView for items with SwipeViews beetween items? How to implement with ViewPager? I try to develop some examples, but didn't work. I would be grateful if someone help me.
So first create a Fragment for your detail. This is for a single detail. The detail that you'll swipe. So apply your layout to this.
#SuppressLint("ValidFragment")
public class Detail extends Fragment {
private final String detail;
public DetailView(String detail) {
this.detail = detail;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detailfragment, container, false);
TextView textView = (TextView) view.findViewById(R.id.detailText);
textView.setText(detail);
return view;
}
}
Now create your Activity. This is the Activity that you will go when you clicked. Now the code adds a Fragment for every detail.
public class Main extends FragmentActivity {
public static ViewPager mPager;
private MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPager = (ViewPager) findViewById(R.id.viewPager1);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
//The count of details. This will return 5 swipeable views.
return 5;
}
#Override
public Fragment getItem(int position) {
return new Detail("I'm a detail!");
}
}
}
This will create 5 details with text "I'm a detail!". Now, i assume you are using ArrayList that storing details. Then you can get the details like this:
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm, ArrayList<HashMap<String, String>> d) {
super(fm);
data = d;
}
#Override
public int getCount() {
return 5;
}
#Override
public Fragment getItem(int position) {
HashMap<String, String> map = new HashMap<String, String>();
map = data.get(position);
Log.d("", data.get(position).toString());
return new Detail(map.get('KeyForYourDetail'));
}
}
Also on your MainActivity change
mAdapter = new MyAdapter(getSupportFragmentManager());
to this
mAdapter = new MyAdapter(getSupportFragmentManager(), yourArrayList);
EDIT
Let's start from the beginning. First, you have your MainActivity which contains a ListView. In the ListView, you are calling items from ArrayList. When you click a item, you get the detail about it from (?). Now my above code can't do that. You have to do that your own first. After you get the detail, just replace the title part below. To summarize, the code i post should work if you can get the "detail", if you don't know how to get detail, then you should create another question.
return new Detail(title);
EDIT 2
OK, here is the other part. Below code is for FragmentActivity.
First, we need to declare our adapter and ViewPager.
public static ViewPager mPager;
private MyAdapter mAdapter;
ArrayList<HashMap<String, String>> detailList= new ArrayList<HashMap<String, String>>();
MyAdapter is the adapter that puts the details into ViewPager. To hold details, we also need an ArrayList as i declared above. Now, you said you don't have problem with parsing. So I'm skipping that part. While you're parsing, I assume you are using NodeList(i took that part from here)
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes
for (int i = 0; i < nl.getLength(); i++) {
String name = parser.getValue(e, KEY_NAME); // name child value
String cost = parser.getValue(e, KEY_COST); // cost child value
String description = parser.getValue(e, KEY_DESC); // description child value
}
Inside of your for loop, create a HashMap like this
HashMap<String, String> map = new HashMap<String, String>();
Remember while we were creating our ArrayList? It's object was HashMap. Now we are going to fill our data to map, then add map to ArrayList. (Again, this goes inside of for loop)
map.put(TAG_DETAIL, detail);
detailList.add(map);
Now this part is over, only thing left is setting the adapter.
mAdapter = new MyAdapter(getSupportFragmentManager(), detailList);
mPager.setAdapter(mAdapter);
And we are done! Let me explain what's going to happen next. Do you remember our adapter?
public MyAdapter(FragmentManager fm, ArrayList<HashMap<String, String>> d) {
super(fm);
data = d;
}
Here as you see, it takes a FragmentManger and an ArrayList with Hashmap inside of it. we set those with getSupportFragmentManager() and detailList. Adapter takes the detailList with details inside of it, then creates Fragments with it. I hope it was clear enough. If wasn't, ask again.
This is the code of MyAdapter.java:
public class MyAdapter extends ArrayAdapter {
ImageLoader imageLoader;
DisplayImageOptions options;
public MyAdapter(Context ctx, int textViewResourceId, List<NewsFeed> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
/*
* (non-Javadoc)
* #see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*
* This method is responsible for creating row views out of a StackSite object that can be put
* into our ListView
*/
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("Feed", "getView pos = " + pos);
// if(null == row){
// //No recycled View, we have to inflate one.
// LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// row = (RelativeLayout)inflater.inflate(R.layout.list_item, null);
// }
if (pos != 0){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.list_item, null);
}
else
{
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.list_first_item, null);
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView titleTxt = (TextView)row.findViewById(R.id.titleTxt);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
//Initially we want the progress indicator visible, and the image invisible
indicator.setVisibility(View.VISIBLE);
iconImg.setVisibility(View.INVISIBLE);
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
imageLoader.displayImage(getItem(pos).getImgUrl(), iconImg,options, listener);
//Set the relavent text in our TextViews
titleTxt.setText(getItem(pos).getTitle());
return row;
}
}

Categories

Resources