I am currently setting content for my tabs like
TabSpec spec1=tabHost.newTabSpec("TAB 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("", ressources.getDrawable(R.drawable.image_large));
But how can set activity as its content for this
spec1.setContent(ProfileMenuAllTopics.this,MainActivity.class);
It says it is not applicable for this
edited:
Can you help on this how to change it
public class ProfileMenuAllTopics extends Fragment {
SessionManager session;
JSONObject jsonobject,jsonobjectTwo;
JSONArray jsonarray,jsonarrayTwo;
ListView listview,listviewTwo;
ListViewAdapter adapter,adapterTwo;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> arraylistTwo;
static String TOPICID = "topicID";
static String RANK = "topicName";
static String COUNTRY = "topicPhone";
static String TOPICPHONE = "topicPhone";
static String POPULATION = "topicDesc";
static String FLAG = "topicImage";
static String TALKTIME = "balanceTalkTime";
private static String KEY_SUCCESS = "success";
RelativeLayout webViewHolderLayout,searchRelativeView,searchRelativeViewMyLists;
String UserID;
ImageView profile_btn;
private View view;
private TransparentProgressDialog pd;
private Handler h;
private Runnable r;
String tabClicked;
JSONObject whatAreYouLooking;
JSONObject myTopicsList;
Button load_more_btn;
Button loadMoreMyTopics;
int maxRecordsHere = 10;
int maxMyRecordsHere = 10;
TabHost tabHost;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi,SetJavaScriptEnabled")
#SuppressWarnings("deprecation")
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
view = inflater.inflate(R.layout.profile_menu_topics_list, null);
h = new Handler();
pd = new TransparentProgressDialog(inflater.getContext(), R.drawable.myspinner);
r =new Runnable() {
#Override
public void run() {
if (pd.isShowing()) {
pd.dismiss();
}
}
};
session = new SessionManager(inflater.getContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
UserID = user.get(SessionManager.KEY_USER_ID);
Resources ressources = getResources();
load_more_btn = (Button) view.findViewById(R.id.loadMoreTopics);
loadMoreMyTopics = (Button) view.findViewById(R.id.loadMoreMyTopics);
tabHost=(TabHost)view.findViewById(R.id.tabHost);
webViewHolderLayout = (RelativeLayout) view.findViewById(R.id.webViewHolder);
searchRelativeView = (RelativeLayout) view.findViewById(R.id.searchRelativeView);
searchRelativeViewMyLists = (RelativeLayout) view.findViewById(R.id.searchRelativeViewMyLists);
Bundle args = getArguments();
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec("TAB 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("", ressources.getDrawable(R.drawable.topics_image_large));
TabSpec spec2=tabHost.newTabSpec("TAB 2");
spec2.setIndicator("", ressources.getDrawable(R.drawable.my_calls_large));
spec2.setContent(R.id.tab2);
TabSpec spec3=tabHost.newTabSpec("TAB 3");
spec3.setContent(R.id.tab3);
spec3.setIndicator("", ressources.getDrawable(R.drawable.how_it_works_large));
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#2AC4EA"));
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#FFFFFF"));
whatAreYouLookingFor();
myTopicsTab();
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#2AC4EA"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#FFFFFF"));
int selectTabHere = tabHost.getCurrentTab();
if(selectTabHere==0){
pd.show();
tabValueZero();
h.postDelayed(r,5000);
}else if(selectTabHere==1){
pd.show();
tabValueOne();
h.postDelayed(r,5000);
}else if(selectTabHere==2){
pd.show();
tabValueTwo();
h.postDelayed(r,5000);
}
}
});
load_more_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pd.show();
maxRecordsHere = maxRecordsHere + 10;
getPaging(whatAreYouLooking,maxRecordsHere);
h.postDelayed(r,5000);
}
});
loadMoreMyTopics.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pd.show();
maxMyRecordsHere = maxMyRecordsHere + 10;
getPagingMyTopics(whatAreYouLooking,maxRecordsHere);
h.postDelayed(r,5000);
}
});
tabValueZero();
return view;
}
private void whatAreYouLookingFor(){
UserFunctions userFunction = new UserFunctions();
whatAreYouLooking = userFunction.getTopicsList();
getPaging(whatAreYouLooking,maxRecordsHere);
}
private void myTopicsTab(){
UserFunctions userFunction = new UserFunctions();
myTopicsList = userFunction.getMyTabTopicsList(UserID);
getPagingMyTopics(myTopicsList,maxMyRecordsHere);
}
public void getPaging(JSONObject whatAreYouLooking,int maxRecords){
arraylist = new ArrayList<HashMap<String, String>>();
try {
if (whatAreYouLooking.getString(KEY_SUCCESS) != null) {
String search_res = whatAreYouLooking.getString(KEY_SUCCESS);
if(Integer.parseInt(search_res) == 1){
jsonarray = whatAreYouLooking.getJSONArray("result");
JSONArray jsonWhatAreYouLookingArray = new JSONArray(whatAreYouLooking.optString("result"));
int totalTopics = jsonWhatAreYouLookingArray.length();
if(totalTopics<=maxRecords){
load_more_btn.setVisibility(View.GONE);
}
for (int w = 0; w < maxRecords; w++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonLookingObject = jsonWhatAreYouLookingArray.getJSONObject(w);
map.put("topicID", jsonLookingObject.getString("topicID"));
map.put("Name", jsonLookingObject.getString("Name"));
map.put("Phone",jsonLookingObject.getString("Phone"));
arraylist.add(map);
listview = (ListView) view.findViewById(R.id.listview);
adapter = new ListViewAdapter(this.getActivity(), arraylist);
listview.setAdapter(adapter);
}
}else{
}
}else{
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
public void getPagingMyTopics(JSONObject myTopicsList,int maxMyRecordsHere){
arraylistTwo = new ArrayList<HashMap<String, String>>();
try {
if (myTopicsList.getString(KEY_SUCCESS) != null) {
String search_res_Two = myTopicsList.getString(KEY_SUCCESS);
if(Integer.parseInt(search_res_Two) == 1){
jsonarrayTwo = myTopicsList.getJSONArray("result");
JSONArray jsonWhatAreYouLookingArrayTwo = new JSONArray(myTopicsList.optString("result"));
int totalTopics = jsonWhatAreYouLookingArrayTwo.length();
if(totalTopics<=maxMyRecordsHere){
loadMoreMyTopics.setVisibility(View.GONE);
}
for (int w = 0; w < maxMyRecordsHere; w++) {
HashMap<String, String> mapTwo = new HashMap<String, String>();
JSONObject jsonLookingObjectTwo = jsonWhatAreYouLookingArrayTwo.getJSONObject(w);
mapTwo.put("topicID", jsonLookingObjectTwo.getString("topicID"));
mapTwo.put("Name", jsonLookingObjectTwo.getString("Name"));
mapTwo.put("Phone",jsonLookingObjectTwo.getString("Phone"));
arraylistTwo.add(mapTwo);
listviewTwo = (ListView) view.findViewById(R.id.listviewTwo);
adapterTwo = new ListViewAdapter(this.getActivity(), arraylistTwo);
listviewTwo.setAdapter(adapterTwo);
}
}else{
}
}else{
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
private void setWebViewHowItworks(){
WebView wv;
wv = (WebView) view.findViewById(R.id.webView1);
wv.setBackgroundColor(0);
wv.setBackgroundResource(android.R.color.black);
wv.setWebChromeClient(new WebChromeClient());
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setLoadWithOverviewMode(true);
wv.addJavascriptInterface(this, "webConnector");
wv.addJavascriptInterface(this, "toaster");
wv.clearView();
wv.loadUrl("www.google.com");
wv.requestLayout();
}
private class TransparentProgressDialog extends Dialog {
private ImageView iv;
public TransparentProgressDialog(Context context, int resourceIdOfImage) {
super(context, R.style.TransparentProgressDialog);
WindowManager.LayoutParams wlmp = getWindow().getAttributes();
wlmp.gravity = Gravity.CENTER_HORIZONTAL;
getWindow().setAttributes(wlmp);
setTitle(null);
setCancelable(false);
setOnCancelListener(null);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
iv = new ImageView(context);
iv.setImageResource(resourceIdOfImage);
layout.addView(iv, params);
addContentView(layout, params);
}
#Override
public void show() {
super.show();
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f , Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(3000);
iv.setAnimation(anim);
iv.startAnimation(anim);
}
}
public void tabValueZero(){
searchRelativeView.setVisibility(View.VISIBLE);
searchRelativeViewMyLists.setVisibility(View.GONE);
webViewHolderLayout.setVisibility(View.GONE);
}
public void tabValueOne(){
searchRelativeView.setVisibility(View.GONE);
searchRelativeViewMyLists.setVisibility(View.VISIBLE);
webViewHolderLayout.setVisibility(View.GONE);
}
public void tabValueTwo(){
searchRelativeView.setVisibility(View.GONE);
searchRelativeViewMyLists.setVisibility(View.GONE);
webViewHolderLayout.setVisibility(View.VISIBLE);
setWebViewHowItworks();
}
}
below is edited code where I have given one sample to include Activity inside Fragment Tabs. Please let me know in case you couldn't understand anything:
//FragmentActivity having tabs
package com.example.tabhost;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
Context mContext;
Intent mIntent;
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapterActivity mTabsAdapter;
//Setup tab
private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
mTabsAdapter = new TabsAdapterActivity(this, mTabHost, mViewPager);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
setupTabHost();
addTab(R.string.mycards,"My Cards Category", MyCardsActivity.class); //My Cards
addTab(R.string.yourcards,"Your Cards Category", YourCardsActivity.class); //Shared Cards
}
//Add tab
private void addTab(int headingTextId, String tabSpec, Class<?> fragmentclass){
LayoutInflater inflater_mycard = getLayoutInflater();
View view = inflater_mycard.inflate(R.layout.tab_style, null);
TextView tab_heading = (TextView) view.findViewById(R.id.tab_heading);
tab_heading.setText(getResources().getString(headingTextId));
mTabsAdapter.addTab(mTabHost.newTabSpec(tabSpec).setIndicator(view), fragmentclass, null);
}
}
//TabsAdapter designed to include Activity
package com.example.tabhost;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
import java.util.ArrayList;
import com.example.tabhost.TabsAdapterFragment.DummyTabFactory;
import com.example.tabhost.TabsAdapterFragment.TabInfo;
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public class TabsAdapterActivity extends PagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final Rect mTempRect = new Rect();
private TabHost.OnTabChangeListener mOnTabChangeListener;
static final class TabInfo {
public final String tag;
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapterActivity(Activity activity, TabHost tabHost, ViewPager pager) {
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Class<? extends TabInfo> instantiateItem(ViewGroup container, int position) {
/*View view = mTabs.get(position).view;
container.addView(view);
return view;*/
return mTabs.get(position).getClass();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public void setOnTabChangedListener(TabHost.OnTabChangeListener listener) {
mOnTabChangeListener = listener;
}
#Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
if (mOnTabChangeListener != null) {
mOnTabChangeListener.onTabChanged(tabId);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
// Scroll the current tab into visibility if needed.
View tab = widget.getChildTabViewAt(position);
mTempRect.set(tab.getLeft(), tab.getTop(), tab.getRight(), tab.getBottom());
widget.requestRectangleOnScreen(mTempRect, false);
// Make sure the scrollbars are visible for a moment after selection
/*final View contentView = mTabs.get(position).view;
if (contentView instanceof CaffeinatedScrollView) {
((CaffeinatedScrollView) contentView).awakenScrollBars();
}*/
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
//-------Supporting XML layouts & drawables-----------
// tab_style.xml place inside layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabsLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tab_bg_selector"
android:gravity="center"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:id="#+id/tab_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#drawable/tab_text_selector"
android:textSize="15sp" />
</LinearLayout>
//place below in drawable folder
//tab_bg_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabsLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tab_bg_selector"
android:gravity="center"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:id="#+id/tab_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#drawable/tab_text_selector"
android:textSize="15sp" />
</LinearLayout>
//tab_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:angle="-90"
android:centerColor="#2A85C4"
android:endColor="#1B73AD"
android:startColor="#1B73AD" />
</shape>
//tab_bg_unselected.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:angle="-90"
android:centerColor="#424242"
android:endColor="#5C5C5C"
android:startColor="#5C5C5C" />
</shape>
//tab_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#android:color/white"/>
<item android:state_focused="true" android:color="#android:color/white"/>
<item android:state_pressed="true" android:color="#android:color/white"/>
<item android:color="#f8f8f8"/>
</selector>
Related
I have ListView which brings data from server using AsyncTask. After that onItemClick starts a new Activity which should show more detailed info of the clicked item from the ListView. Pretty simple . But problem is the individual pages should work like 9GAG android app (i.e Swipeable Fragment with ViewPager). The detail info is much more. What are your suggestion for design layout of that page. Currently I am using ViewPager on that single page and Design the fragment to get the required thing.
Code
public class IndividualPage extends ActionBarActivity{
ArrayList<Item> arrayOfList;
ViewPager pager;
CountryPageAdapter pageAdapter;
private ProgressBar mProgress;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.secondpage);
mProgress = (ProgressBar) findViewById(R.id.linear_progress_bar);
new FilteredResult().execute();
pager = (ViewPager)findViewById(R.id.viewpager);
}
private List<Fragment> getFragments() {
List<Fragment> frags = new ArrayList<Fragment>();
System.out.println("fragments main ayya hai");
cats=arrayOfList;
for(int i = 0;i<cats.size();i++ ) {
System.out.println("number : "+i+"::"+cats.get(i).getSector());
frags.add(prepareFragment(cats.get(i).getImage(),cats.get(i).getName(),cats.get(i).getLocation(),cats.get(i).getSector(),cats.get(i).getStatus(),cats.get(i).getFounded(),cats.get(i).getFundRaising()));
}
return frags;
}
Fragment prepareFragment(String image,String name,String location,String Expertise,String sector,int founded,String fund) {
CountryFragment cf = new CountryFragment();
Bundle args = new Bundle();
args.putString(CountryFragment.STARTUP_IMAGE, image);
args.putString(CountryFragment.STARTUP_NAME, name);
args.putString(CountryFragment.STARTUP_LOCATION, location);
args.putString(CountryFragment.STARTUP_EXP, Expertise);
args.putString(CountryFragment.STARTUP_SEC, sector);
args.putInt(CountryFragment.STARTUP_FOUNDED, founded);
args.putString(CountryFragment.STARTUP_FUND, fund);
cf.setArguments(args);
return cf;
}
[![public class FilteredResult extends AsyncTask<String, Void, String> {
//onpreexcute nothing doing great in this
//onbackground
#Override
protected void onPostExecute(String result) {
List<Fragment> fragments = getFragments();
pageAdapter = new CountryPageAdapter(getSupportFragmentManager(), fragments);
pager.setAdapter(pageAdapter);
}
}]
I personally prefer ViewPagers to ScrollViews as they do not keep all of the fragment/views in the memory.
Also each individual item is independent of the other ones. For example if you want to be able to implement vertical scrolling for each item you cannot do it with HorizontalScrollView as all the views will scroll together.
Even im having the same kind of design i have done like this
Class File
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.widget.LinearLayout;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
public class TurfDetailsActivity extends BaseActivity{
private SliderLayout mDemoSlider;
ViewPager pager;
private ViewPager viewPager;
private TurfDetailsViewPagerAdapter mAdapter;
private ActionBar mActionBar;
LinearLayout SliderImg;
private PagerSlidingTabStrip tabs;
String Venue;
public static Bundle b;
public static ArrayList<ReviewModel> reviewList;
public static ArrayList<TimingModel> timigList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_turf_details_1);
mDemoSlider = (SliderLayout)findViewById(R.id.turf_details_slider);
reviewList = new ArrayList<ReviewModel>();
timigList = new ArrayList<TimingModel>();
actionBarIdForAll("Turf Details");
String data = getIntent().getStringExtra("data");
Bundle object = getDataObject(data);
imageSlider(data);
tabs = (PagerSlidingTabStrip)findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.pager);
mActionBar = getSupportActionBar();
mAdapter = new TurfDetailsViewPagerAdapter(getSupportFragmentManager(), object);
viewPager.setAdapter(mAdapter);
mActionBar.setDisplayHomeAsUpEnabled(true);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
tabs.setViewPager(viewPager);
tabs.setIndicatorColor(Color.parseColor("#ffffff"));
tabs.setTextColor(Color.parseColor("#ffffff"));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
outState = b;
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
b = savedInstanceState;
}
private Bundle getDataObject(String data) {
// TODO Auto-generated method stub
ReviewModel mReviewModel;
TimingModel mTimingModel;
b = new Bundle();
try {
JSONObject obj = new JSONObject(data).getJSONArray("venue").getJSONObject(0);
b.putString("vid", obj.getString("vid"));
b.putString("venueName", obj.getString("venue_name"));
Venue = obj.getString("venue_name");
b.putString("location", obj.getString("location"));
b.putString("address", obj.getString("address"));
b.putString("contact", obj.getString("booking_contact"));
b.putString("turfSize", obj.getString("turf_size"));
b.putString("formats", obj.getString("preferred_format"));
b.putString("floodlights", obj.getString("floodlights"));
b.putString("ball", obj.getString("ball"));
b.putString("shoeType", obj.getString("shoe_type"));
b.putString("parking", obj.getString("parking"));
b.putString("refreshments", obj.getString("refreshments"));
b.putString("washrooms", obj.getString("washrooms"));
b.putString("bibs", obj.getString("bibs"));
b.putString("otherGames", obj.getString("other_games_played"));
b.putString("coaching", obj.getString("coaching"));
b.putString("stands", obj.getString("stands"));
b.putString("website", obj.getString("website"));
b.putString("latitude", obj.getString("latitude"));
b.putString("longitude", obj.getString("longitude"));
b.putString("cost", obj.getString("cost"));
b.putString("rating", obj.getString("rating"));
b.putString("createdDate", obj.getString("created_date"));
b.putString("updatedDate", obj.getString("updated_date"));
JSONArray array = new JSONObject(data).getJSONArray("reviews");
if(array.length()!=0){
for(int i=0;i<array.length();i++){
JSONObject obj11 = array.getJSONObject(i);
String vid = obj11.getString("vid");
String uid = obj11.getString("uid");
String email = obj11.getString("email");
String created_date = obj11.getString("created_date");
String review = obj11.getString("review");
String review_user_image = obj11.getString("image");
String review_user_name = obj11.getString("name");
b.putString("review", review);
b.putString("review_user_image", review_user_image);
b.putString("review_user_name", review_user_name);
mReviewModel = new ReviewModel(vid, uid, review, review_user_image, review_user_name, email, created_date);
reviewList.add(mReviewModel);
}
}else {
b.putString("Review_count", "0");
}
JSONArray arrayCost = new JSONObject(data).getJSONArray("cost");
for(int i=0;i<arrayCost.length();i++){
JSONObject obj12 = arrayCost.getJSONObject(i);
String vid = obj12.getString("vid");
String tid = obj12.getString("tid");
String timing = obj12.getString("timing");
String created_date = obj12.getString("created_date");
String weekdays = obj12.getString("weekdays");
String weekends = obj12.getString("weekends");
b.putString("timing", timing);
b.putString("weekdays", weekdays);
b.putString("weekends", weekends);
Log.e("timing", timing);
Log.e("weekdays", weekdays);
Log.e("weekends", weekends);
mTimingModel = new TimingModel(vid, tid, timing, weekdays, weekends);
timigList.add(mTimingModel);
}
} catch (Exception e) {
// TODO: handle exception
}
return b;
}
public void imageSlider(String data){
try {
JSONArray array = new JSONObject(data).getJSONArray("media");
if(array.length()!=0){
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
String url = obj.getString("path");
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView.description(Venue).image(url).setScaleType(BaseSliderView.ScaleType.Fit);
//add your extra information
textSliderView.getBundle().putString("extra","Where is my turf");
mDemoSlider.addSlider(textSliderView);
}
}else{
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView .description("Where is my turf").image(R.drawable.ic_launcher).setScaleType(BaseSliderView.ScaleType.Fit);
//add your extra information
textSliderView.getBundle() .putString("extra","Where is my turf");
mDemoSlider.addSlider(textSliderView);
}
} catch (Exception e) {
e.printStackTrace();
}
mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
mDemoSlider.setCustomAnimation(new DescriptionAnimation());
mDemoSlider.setDuration(3000);
}
}
ADAPTER
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TurfDetailsViewPagerAdapter extends FragmentPagerAdapter {
private Bundle data;
public TurfDetailsViewPagerAdapter(FragmentManager fm, Bundle data) {
super(fm);
this.data = data;
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
if (position == 0)
{
return "ABOUT";
}
if (position == 1)
{
return "FEATURES";
}
if (position == 2)
{
return "COST";
}
if (position == 3)
{
return "REVIEWS";
}
return null;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new AboutFragment(data);
case 1:
return new FeaturesFragment();
case 2:
return new CostFragment();
case 3:
return new ReviewsFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
XML Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/image_forward"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_weight=".35" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.daimajia.slider.demo.ImageSliderActivity" >
<com.daimajia.slider.library.SliderLayout
android:id="#+id/turf_details_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom:auto_cycle="true"
custom:indicator_visibility="visible"
custom:pager_animation="Accordion"
custom:pager_animation_span="1100" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:layout_weight=".65"
android:orientation="vertical" >
<com.PACKAGE.customviews.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#5e5b5b"
android:paddingLeft="3dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
Result Image
IF YOU NEED ANY KIND OF HELP FEEL FREE TO ASK.....Happeee...Programming....
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'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 have one main activity which is fragment activity here I am setting two tabs with two fragments A and B in the B fragment I have one button when the user click on the button I want to change fragment B to fragment C. But the tabs above are visible...
How I can achieve replacing fragments inside tabs?
Any solution are greatly appreciated.
Basic concept- We can achieve this by creating a container. Each tab will be assigned with a specific container. Now when we need a new fragment then we will replace same using this container.
Kindly follow undermentioned code step by step to have better understanding.
Step-1: Create Tabs for your app. Say "Home.java". It will contain code for creating tabs using fragment.
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.widget.TextView;
import app.drugs.talksooner.container.GoContainerFragment;
import app.drugs.talksooner.container.LearnContainerFragment;
import app.drugs.talksooner.container.MoreContainerFragment;
import app.drugs.talksooner.container.TalkContainerFragment;
import app.drugs.talksooner.container.WatchContainerFragment;
import app.drugs.talksooner.utils.BaseContainerFragment;
public class Home extends FragmentActivity {
private static final String TAB_1_TAG = "tab_1";
private static final String TAB_2_TAG = "tab_2";
private static final String TAB_3_TAG = "tab_3";
private static final String TAB_4_TAG = "tab_4";
private static final String TAB_5_TAG = "tab_5";
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
initView();
}
private void initView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Learn"), LearnContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);
/* Increase tab height programatically
* tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150;
*/
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(10);
}
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_4_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_5_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
}
Your home.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
Step-2: Define Base container fragment which will be helpful for backtracking and replacment of fragments "check out replaceFragement() ". Our class "BaseContainerFragment.java"
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import app.drugs.talksooner.R;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
Step3: Now here I am considering for one fragment only hoping that rest can be handled by you in same fashion. Defining container Fragment class. Each tab will have specific container. Say TalkContainerFragment.java for first tab
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import app.drugs.talksooner.R;
import app.drugs.talksooner.Talk;
import app.drugs.talksooner.utils.BaseContainerFragment;
public class TalkContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("test", "tab 1 oncreateview");
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("test", "tab 1 container on activity created");
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
private void initView() {
Log.e("test", "tab 1 init view");
replaceFragment(new Talk(), false);
}
}
It's xml file. "container_fragment.xml" this xml container contains frameLayout. we will use this id to replace different Fragments.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Your main class. "Talk.java"
public class Talk extends Fragment {
/** Define global variables over here */
//private ProgressDialog pDialog;
StaticApiList sal;
TalkModelAll tma;
JSONObject myJasonObject = null;
private ListView lv;
private ArrayList<TalkModelAll> m_ArrayList = null;
//ArrayList<String> stringArrayList = new ArrayList<String>();
TalkArrayAdapter taa;
Set<String> uniqueValues = new HashSet<String>();
TextView rowTextView = null;
boolean vivek = false;
int postid;
String title;
String thumsrc;
String largeimg;
String excert;
String description;
String cat;
String myUrl;
String jsonString;
int mCurCheckPosition;
String check_state = null;
String ccc;
LinearLayout myLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.talk, container, false);
Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Here TalkDetail is name of class that needs to open
TalkDetail fragment = new TalkDetail();
// if U need to pass some data
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("cat", m_ArrayList.get(arg2).cat);
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
return rootView;
}
}
That's it. You are good to go. The whole magic lies in calling R.id. instead of R.layout.
Cheers!
I am trying to add the same class several times to a viewpager to show different info which is read from a sqlite DB. The thing is when the view is created, always override the objects, textviews etc..., in the current view and not in the fragment for each page.
names = new ArrayList<String>();
for (int d : descritions) {
Description temp = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, d, Locale.getDefault().getLanguage(),
GSSettings.DEFAULTLANGUAGE, false);
names.add(temp.getTitle());
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// mViewPager.setCurrentItem(0);
mViewPager.refreshDrawableState();
...
How can I avoid this behavior?
thanks.
EDIT:
I added more code to clarify my question:
framecompany100.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ly_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbarDefaultDelayBeforeFade="500"
android:scrollbarFadeDuration="200"
android:scrollbarThumbVertical="#drawable/scrollbar_vertical_thumb_company" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Gallery
android:id="#+id/ga_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp" />
<RelativeLayout
android:id="#+id/ly_details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ga_image" >
<ImageView
android:id="#+id/iv_options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:src="#drawable/ic_button_options" />
<RelativeLayout
android:id="#+id/ly_details_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_toRightOf="#+id/iv_options"
android:background="#77ffffff" >
<TextView
android:id="#+id/tv_address" android:text="kldfjhskdjhfksj"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="15sp" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/tv_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ly_details"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
and the class for this layout:
FrameCompany100.java
public class FrameCompany100 extends Fragment implements OnClickListener,
PictureUpdater, FragmentName {
private Bundle data = new Bundle();
private Gallery image;
private Description description;
private BaseAdapter adapter;
private String db_path;
private GuiParams main_params;
private Company company;
private String name = "";
#Override
public void onCreate(Bundle savedInstanceState) {
data = this.getArguments();
if (savedInstanceState != null)
data = savedInstanceState;
db_path = "/data/data/" + getActivity().getPackageName()
+ GSSettings.DB_PATH;
description = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, data.getInt("descriptionId"), Locale
.getDefault().getLanguage(), "es", false);
company = DBCompanies.getCompany(db_path, GSSettings.DBCODE,
description.getCompanyId());
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.framecompany100, container, false);
}
void init() {
try {
Display display = getActivity().getWindowManager()
.getDefaultDisplay();
int height = display.getHeight();
final int width = display.getWidth();
// params
main_params = DBCompanies.getGuiParams(db_path, GSSettings.DBCODE,
description.getCompanyId(), GSSettings.body);
if (main_params == null || main_params.getBackgroundcolor() == null
|| main_params.getBackgroundcolor().equals("")
|| main_params.getTextcolor() == null
|| main_params.getTextcolor().equals(""))
main_params = DBApp.getGuiParam(db_path, GSSettings.DBCODE,
GSSettings.body);
// main Layout
RelativeLayout ly_main = (RelativeLayout) getActivity()
.findViewById(R.id.ly_main);
try {
ly_main.setBackgroundColor(Color.parseColor(main_params
.getBackgroundcolor()));
} catch (Exception e) {
}
Typeface font_body = null;
try {
font_body = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/" + main_params.getFont());
} catch (Exception e) {
font_body = Typeface.createFromAsset(
getActivity().getAssets(),
"fonts/"
+ DBApp.getGuiParam(db_path, GSSettings.DBCODE,
GSSettings.body).getFont());
}
TextView tv_description = (TextView) getActivity().findViewById(
R.id.tv_description);
try {
tv_description.setTextColor(Color.parseColor(main_params
.getTextcolor()));
} catch (Exception e) {
}
if (description == null) {
tv_description.setText(R.string.nodescription);
} else {
tv_description.setText(description.getText());
}
TextView tv_address = (TextView) getActivity().findViewById(
R.id.tv_address);
try {
tv_address.setTextColor(Color.parseColor(main_params
.getTextcolor()));
} catch (Exception e) {
}
.....
}
#Override
public void onResume() {
init();
// ((MainLayout) getActivity()).setDescription(description);
super.onResume();
}
the FragmentPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Description temp = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, descritions[i], Locale.getDefault()
.getLanguage(), GSSettings.DEFAULTLANGUAGE, false);
Fragment fragment = null;
try {
fragment = new CompanyLayout100();
((FragmentName) fragment).setName(temp.getTitle());
Bundle bundle = new Bundle();
bundle.putInt("descriptionId", temp.getId());
fragment.setArguments(bundle);
} catch (Exception e) {
}
return fragment;
}
#Override
public int getCount() {
return descritions.length;
// return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
String name = "";
try {
name = names.get(position);
} catch (Exception e) {
}
return name;
}
}
what's happening is, the viewpager create the view for these frames but always is entering the data in the visible frame. I think is because the layout.xml is the same so there is only one id and all object are pointing at the visible layout.
You need a FragmentPagerAdapter that creates the instance ...
public class PagerAdapter extends FragmentPagerAdapter {
int pages;
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public int getCount() {
return pages;
}
#Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position);
}
public void setPages(int no) {
pages = no;
}
}
So in the main activity you attach the PagerAdapter ...
adapter = new PagerAdapter(getSupportFragmentManager());
adapter.setPages(noPages);
pager.setAdapter(adapter);
Finally you need your Fragment including the newInstance method. Check out this http://android-developers.blogspot.de/2011/08/horizontal-view-swiping-with-viewpager.html for more.
Cheers!
Edit #1: MyFragment; note: it is essential to pass the position as an argument
public class MyFragment extends SherlockFragment {
private static final String KEY_POSITION="position";
static MyFragment newInstance(int position) {
MyFragment frag=new MyFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.editor, container, false);
EditText editor=(EditText)result.findViewById(R.id.editor);
int position=getArguments().getInt(KEY_POSITION, -1);
editor.setHint(String.format(getString(R.string.hint), position + 1));
return(result);
}
}