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!
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 have to change the views on swipe. This can be obtained through view pager. But I have 60 views and creating 60 different fragment will not be a good approach.
Please someone guide me what will be the best way to design swiping 60 views.
Firstly create one fragment where you can inflate different views using "position" parameter as follow..
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
View mainView;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(position==1){
mainview = inflater.inflate(R.layout.layout1, null);
}else if(position==2){
mainview =inflater.inflate(R.layout.layout2, null);
.
.
.
.
}else if(position==50){
mainview =inflater.inflate(R.layout.layout50, null);
}
return mainView;
}
}
Now in Your MainActivity Create an Adapter that extends FragmentPagerAdpater and in getItem() method create the instances of previously create fragment as follow
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Title1", "Title2"...., "Title50"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
Then finally add this in your Activity's OnCreat() method...
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
yourViewPager.setAdapter(adapter);
Thus you will have to create single fragment and use it for multiple views.
Thank you. Hope it helps..!!
You can safely use the ViewPager with an implementation of FragmentStatePagerAdapter. The adapter will optimize the memory usage by destroying fragments that are not visible at a given moment. Check the documentation for details and code sample.
Below is the complete code to add Fragments to a View pager.
Since this is just a demonstration I have used just a textView and each fragment added will have a random colour.On clicking a button you can add as many fragments as you want.On clicking the Page you can just remove it from the View Pager.You can move from one Page to another in a View Pager by Swiping to the right or left.
MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends FragmentActivity {
private MyPagerAdapter mpg;
private ArrayList<MyFragment> fragmentlist = new ArrayList<>();
public FragmentManager fmr = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
mpg = new MyPagerAdapter(fmr,fragmentlist);
pager.setAdapter(mpg);
for (int q = 0; q < 5; q++) {
int r = new Random().nextInt(100) + 155;
int g = new Random().nextInt(100) + 155;
int b = new Random().nextInt(100) + 155;
fragmentlist.add(MyFragment.newInstance(q, "Page number: " + (q + 1), Color.rgb(r, g, b)));
mpg.notifyDataSetChanged();
}
Button B1 = (Button) findViewById(R.id.button);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int r = new Random().nextInt(100) + 155;
int g = new Random().nextInt(100) + 155;
int b = new Random().nextInt(100) + 155;
int count = mpg.getCount();
fragmentlist.add(MyFragment.newInstance(count, "Page number: " + (count+1), Color.rgb(r, g, b)));
mpg.notifyDataSetChanged();
}
});
}
public void delete(int pos) {
int i = 0;
while (i <= fragmentlist.size()) {
if (pos == fragmentlist.get(i).getPosition()) break;
i++;
}
fragmentlist.remove(i);
mpg.notifyDataSetChanged();
}
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<MyFragment> fragmentList;
public MyPagerAdapter(FragmentManager fm, ArrayList<MyFragment> f) {
super(fm);
this.fragmentList = f;
}
#Override
public Fragment getItem(int pos) {
return fragmentlist.get(pos);
}
#Override
public int getCount() {
return fragmentlist.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
MyFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.List;
public class MyFragment extends Fragment {
int pos;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.f_1, container, false);
pos = getArguments().getInt("num");
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("MainActivity", "Deleting at pos - " + pos);
MainActivity activity = (MainActivity) getActivity();
activity.delete(pos);
}
});
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
FrameLayout fl = (FrameLayout) v.findViewById(R.id.frame_layout);
tv.setText(getArguments().getString("msg"));
fl.setBackgroundColor(getArguments().getInt("colour"));
return v;
}
public int getPosition() {
return pos;
}
public static MyFragment newInstance(int num,String text,int clr) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putString("msg", text);
b.putInt("colour", clr);
b.putInt("num",num);
f.setArguments(b);
return f;
}
}
And the xml.files,
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shakthivels.assingment10.MainActivity"
android:id="#+id/r_v"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD a fragment"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
f_1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/av"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/frame_layout">
<TextView
android:id="#+id/tvFragFirst"
android:layout_width="203dp"
android:layout_height="127dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26sp"
android:text="TextView"
android:layout_gravity="center"
android:textColor="#000000" />
</FrameLayout>
</RelativeLayout>
1
2
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 haven't touched this codebase in a couple of months. Now that I've picked it up again, some code that I didn't think I'd changed has stopped working: All listfragment listviews in the app populated by a simplecursoradapter have stopped working and are just blank. At first I thought the cursor or the database was at fault or that perhaps the adapter wasn't being set correctly, so I added some debugging to the onLoadFinished:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
Log.d("IndexListFragment", "Rows returned: " + cursor.getCount());
Log.d("IndexListFragment", cursor.getColumnName(0));
Log.d("IndexListFragment", mAdapter.toString());
Log.d("IndexListFragment", this.getListView().getAdapter().toString());
mAdapter.swapCursor(cursor);
}
This returns what I'd expect:
IndexListFragment: Rows returned: 2324
IndexListFragment: _id
IndexListFragment: android.support.v4.widget.SimpleCursorAdapter#41d06a18
IndexListFragment: android.support.v4.widget.SimpleCursorAdapter#41d06a18
So as far as I can tell, the cursor is there and full of data, but swapping it in doesn't get the listview populated. Any ideas?
For completeness, here's the onCreate where the adapter is created and set:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { GuidebookProvider.COL_NAME,
GuidebookProvider.COL_GRADE };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null, from, to, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
And the onCreateLoader:
#Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle loaderArgs) {
String orderBy = GuidebookProvider.COL_NAME;
String[] projection = new String[] { GuidebookProvider.COL_ID, GuidebookProvider.COL_NAME, GuidebookProvider.COL_GRADE };
return new CursorLoader(getActivity(),
GuidebookProvider.CONTENT_URI_CLIMB, projection, null, null,
orderBy);
}
Edit: I've done a little more work debugging this issue. The fragment works fine if I run it directly from an activity like this:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
public class TestActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
frame.setId(android.R.id.content);
if (savedInstanceState == null) {
Bundle args = new Bundle();
args.putInt(IndexListFragment.ARGUMENT_INDEX_TYPE, IndexListFragment.IndexType.ALPHA.value);
Fragment indexListFragment = new IndexListFragment();
indexListFragment.setArguments(args);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, indexListFragment).commit();
}
}
}
However, calling it as part of a Tab ends up with a blank tab:
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class TestActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tab_host);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle args = new Bundle();
args.putInt(IndexListFragment.ARGUMENT_INDEX_TYPE,
IndexListFragment.IndexType.ALPHA.value);
Drawable drawable = null;
mTabHost.addTab(mTabHost.newTabSpec("A-Z")
.setIndicator("A-Z", drawable), IndexListFragment.class, args);
}
}
Here's my xml for the tabhost:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.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="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
The fact that the fragment populates correctly when called directly but not when called from within a tab seems to show that the problem isn't at all with the cursors or adapters but with the way the listfragment operating inside a tab.
Can anyone point out what I've done wrong (or what's changed in the last couple of updates of the SDK) to break this code? It used to work fine.
This Code may help you just try it
ViewAllLesson.java :
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import com.xyz.R;
import com.xyz.db.LessonDatabaseConnector;
import com.xyz.pojo.AssignmentPojo;
import com.xyz.pojo.LessonPojo;
public class ViewAllLessons extends Fragment {
public LessonDatabaseConnector dao;
private View rootView;
List<LessonPojo> lessons;
ArrayList<String> con = new ArrayList<String>();
LayoutInflater mInflater;
LessonCustomAdapter lessonCustomAdapter;
private ListView listView;
public static CheckBox selectAll;
private Button deleteBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.add_exams);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.lesson_view_all_list, container,
false);
// dao = new AssignmentDatabaseConnector(getActivity());
listView = (ListView) rootView.findViewById(R.id.Lesson_ListAll);
selectAll = (CheckBox) rootView.findViewById(R.id.SelectAll);
deleteBtn = (Button) rootView.findViewById(R.id.LessonDeleteBtn);
Button addNew = (Button) rootView.findViewById(R.id.LessonAddNewBtn);
addNew.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "hi",
// Toast.LENGTH_LONG).show();
Lesson lesson = new Lesson();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, lesson).commit();
}
});
// viewgr.setScrollContainer(false);
dao = new LessonDatabaseConnector(getActivity());
lessons = dao.getAllLessonList();
lessonCustomAdapter = new LessonCustomAdapter(getActivity(), lessons,
this);
listView.setAdapter(lessonCustomAdapter);
/* To Check List View is empty */
if (lessons.size() <= 0) {
View empty = rootView.findViewById(R.id.empty);
ListView list = (ListView) rootView
.findViewById(R.id.Lesson_ListAll);
list.setEmptyView(empty);
listView.setVisibility(0);
empty.setVisibility(1);
}
selectAll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "hi",
// Toast.LENGTH_LONG).show();
if (((CheckBox) v).isChecked()) {
LessonCustomAdapter.flag = true;
lessonCustomAdapter.notifyDataSetChanged();
} else {
LessonCustomAdapter.flag = false;
LessonCustomAdapter.checkedvalue.clear();
lessonCustomAdapter.notifyDataSetChanged();
}
}
});
// Set the list adapter and get TODOs list via DAO
deleteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LessonDatabaseConnector dao = new LessonDatabaseConnector(
getActivity());
for (int i = 0; i < LessonCustomAdapter.checkedvalue.size(); i++) {
//
System.out
.println("===========LessonCustomAdapter.checkedvalue.size()==========SIZE======>>>>"
+ LessonCustomAdapter.checkedvalue.size());
System.out
.println("===========DELETED LESSON=================>>>>"
+ LessonCustomAdapter.checkedvalue.get(i));
dao.DeleteLesson(LessonCustomAdapter.checkedvalue.get(i));
}
LessonCustomAdapter.flag = false;
ViewAllLessons viewAllLessons = new ViewAllLessons();
getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, viewAllLessons)
.commit();
// finish();
}
});
return rootView;
}
private List<AssignmentPojo> getAllAssignmentsList() {
// TODO Auto-generated method stub
return null;
}
}
LessonCustomAdapter :
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.xyz.R;
import com.xyz.pojo.LessonPojo;
public class LessonCustomAdapter extends BaseAdapter {
protected static boolean flag = false;
private TextView mLessonTitle, mLessonDate;
private final Context context;
List<LessonPojo> Lessons;
private ViewAllLessons viewAllLessons;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
private CheckBox SingleChk;
public static ArrayList<Long> checkedvalue = new ArrayList<Long>();
LessonCustomAdapter(Context context, List<LessonPojo> Lessons2,
ViewAllLessons viewAllLessons) {
this.context = context;
this.Lessons = Lessons2;
this.viewAllLessons = viewAllLessons;
for (int i = 0; i < Lessons2.size(); i++) {
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Lessons.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
rowView = inflater.inflate(R.layout.lesson_view_row_list, parent,
false);
}
mLessonDate = (TextView) rowView.findViewById(R.id.LessonDate);
mLessonDate.setText(Lessons.get(position).getLdate());
mLessonTitle = (TextView) rowView.findViewById(R.id.LessonTitle);
mLessonTitle.setText(Lessons.get(position).getLtitle());
SingleChk = (CheckBox) rowView.findViewById(R.id.singleChk);
/*
* if (flag) { System.out.println("66666666666666666666666666666666" +
* flag); for (int i = 0; i < Lessons.size(); i++) {
* SingleChk.setChecked(flag); SingleChk.setEnabled(!flag); }
*
* } else { SingleChk.setChecked(itemChecked.get(position)); }
*/
checkedvalue.clear();
if (ViewAllLessons.selectAll.isChecked()) {
SingleChk.setChecked(true);
Boolean val = false;
for (int i = 0; i < Lessons.size(); i++) {
checkedvalue.add(Long.parseLong(Lessons.get(i).getId()));
System.out
.println("ADD SUCCEFULLYYYYYYYY ====================== "
+ Long.parseLong(Lessons.get(position).getId()));
}
} else {
SingleChk.setChecked(false);
checkedvalue.clear();
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
ViewSingleLesson viewSingleLesson = new ViewSingleLesson();
bundle.putString("ID", Lessons.get(position).getId());
bundle.putString("TITLE", Lessons.get(position).getLtitle());
bundle.putString("COURSE", Lessons.get(position).getLcourse());
bundle.putString("LEVEL", Lessons.get(position).getLlevel());
bundle.putString("CLASS", Lessons.get(position).getLclass());
bundle.putString("DATE", Lessons.get(position).getLdate());
bundle.putString("DESC", Lessons.get(position).getLdesc());
bundle.putString("ATTACH", Lessons.get(position).getLfilepath());
viewSingleLesson.setArguments(bundle);
viewAllLessons.getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, viewSingleLesson)
.commit();
}
});
SingleChk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Boolean val = false;
Toast.makeText(context, "hi " + Lessons.get(position).getId(),
Toast.LENGTH_LONG).show();
if (((CheckBox) v).isChecked()) {
for (int i = 0; i < checkedvalue.size(); i++) {
if (checkedvalue.get(i) == Long.parseLong(Lessons.get(
position).getId())) {
val = true;
System.out
.println("DUPLICATE ====================== "
+ Long.parseLong(Lessons.get(
position).getId()));
} else {
val = false;
}
}
if (val == false) {
checkedvalue.add(Long.parseLong(Lessons.get(position)
.getId()));
System.out
.println("ADD SUCCEFULLYYYYYYYY ====================== "
+ Long.parseLong(Lessons.get(position)
.getId()));
}
} else {
ViewAllLessons.selectAll.setChecked(false);
checkedvalue.remove(Long.parseLong(Lessons.get(position)
.getId()));
System.out
.println("Removed SUCCEFULLYYYYYYYY ====================== "
+ Integer.parseInt(Lessons.get(position)
.getId()));
// itemChecked.set(position, false);
}
}
});
return rowView;
}
}
Got a chance to have a look at this today and finally sorted it out. The problem was in my xml layout setup. Oddly, according to my git repository, this file hasn't changed for 9 months so I guess I was doing something that only worked by accident. I found a tutorial FragmentTabHosts with a different layout and updated my layout to:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</LinearLayout>
That somehow fixed the issue. A bit more hunting around revealed an example layout xml for FragmentTabHost in the TabActivity documentation: http://developer.android.com/reference/android/app/TabActivity.html
I updated to use the version found in the documentation and it also works:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Given I found it in Android's documentation, I'll stick with this version.