Fragment tab content not shown with HoloEverywhere and ActionbarSherlock - android

Hi I'm making this app with two fragments that you can swipe between. The code compiles and runs without crashing and both tabs are shown and you can swipe between the tabs but the tabs have no content. I think this is a problem with the fragments trying to setcontentview. If you need anymore info just ask :)
my main activity
import java.util.ArrayList;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.WindowManager;
public class SwipeTabsMainActivity extends Activity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
TextView tabCenter;
TextView tabText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Stopwatch"),StopWatchFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Timer"), CountdownFragment.class, null);
}
public static class TabsAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(Activity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
the Main Activity's 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/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
my countdown timer fragment
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.internal._View;
import org.holoeverywhere.preference.PreferenceManager;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.Button;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import org.holoeverywhere.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.RelativeLayout;
public class CountdownFragment extends Fragment implements
OnChronometerTickListener {
TextView second, hour, minute;
ImageButton hourup, hourdown, minuteup, minutedown, secondup, seconddown;
Button start, stop;
int hourCount, minCount, secCount;
Context c;
Chronometer count;
boolean viberate, running;
Vibrator v;
boolean startstopshow;
SharedPreferences getPrefs;
View fv = getView();
RelativeLayout rl;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initilize(c);
setClicker();
count.start();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
c = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.countdown, container, false);
rl = (RelativeLayout )inflater.inflate(R.layout.countdown, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
private void initilize(Context c) {
hourup = (ImageButton) rl.findViewById(R.id.hourup);
minuteup = (ImageButton) rl.findViewById(R.id.minuteup);
secondup = (ImageButton) rl.findViewById(R.id.secondup);
hourdown = (ImageButton) rl.findViewById(R.id.hourdown);
minutedown = (ImageButton) rl.findViewById(R.id.minutedown);
seconddown = (ImageButton) rl.findViewById(R.id.seconddown);
start = (Button) rl.findViewById(R.id.start);
stop = (Button) rl.findViewById(R.id.stop);
second = (TextView) rl.findViewById(R.id.second);
minute = (TextView) rl.findViewById(R.id.minute);
hour = (TextView) rl.findViewById(R.id.hour);
hourCount = 0;
minCount = 0;
secCount = 0;
count = (Chronometer) rl.findViewById(R.id.chronometer1);
v = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE);
running = false;
getPrefs = PreferenceManager.getDefaultSharedPreferences(c);
}
#Override
public void onChronometerTick(Chronometer chronometer) {
switch (chronometer.getId()) {
case (R.id.chronometer1):
secCount--;
updateDisplay();
break;
}
}
}
my fragments xml file
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/hourup"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up" />
<ImageButton
android:id="#+id/minuteup"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up" />
<ImageButton
android:id="#+id/secondup"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<org.holoeverywhere.widget.TextView
android:id="#+id/hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00 : "
android:textSize="35sp" />
<org.holoeverywhere.widget.TextView
android:id="#+id/minute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00 : "
android:textSize="35sp" />
<org.holoeverywhere.widget.TextView
android:id="#+id/second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00"
android:textSize="35sp" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/hourdown"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/down" />
<ImageButton
android:id="#+id/minutedown"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/down" />
<ImageButton
android:id="#+id/seconddown"
style="?borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/down" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_weight="50"
android:gravity="bottom"
android:weightSum="100" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true" >
<org.holoeverywhere.internal._View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="1dip"
android:layout_alignParentTop="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:background="?dividerVertical" />
<org.holoeverywhere.internal._View
android:id="#+id/ViewColorPickerHelper"
android:layout_width="1dip"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="4dip"
android:layout_marginTop="4dip"
android:background="?dividerVertical" />
<org.holoeverywhere.widget.Button
android:id="#+id/start"
style="#style/Holo.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/view1"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/stop"
android:text="Start" />
<org.holoeverywhere.widget.Button
android:id="#+id/stop"
style="#style/Holo.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ViewColorPickerHelper"
android:text="Stop" />
</RelativeLayout>
</LinearLayout>
<Chronometer
android:id="#+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Chronometer"
android:textSize="0px"
android:visibility="invisible" />
</RelativeLayout>

I finally found the problem:
You have to replace : super.onCreateView(inflater, container, savedInstanceState); to your countdown view :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.countdown, container, false);
rl = (RelativeLayout )inflater.inflate(R.layout.countdown, container, false);
return v;
}
Here's a screenshot of the result:

i can see that you are using the ActionBarSherlock. try that library : http://viewpagerindicator.com/ . It will help you and it is really easy to customize you tabs and navigation
You can see alot of examples with the app on Google play : https://play.google.com/store/apps/details?id=com.viewpagerindicator.sample&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS52aWV3cGFnZXJpbmRpY2F0b3Iuc2FtcGxlIl0.
Here's an example :
main activity :
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.viewpagerindicator.TabPageIndicator;
public class MainActivity extends SherlockFragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
//Bind the title indicator to the adapter
TabPageIndicator tabIndicator = (TabPageIndicator)findViewById(R.id.titles);
tabIndicator.setViewPager(mViewPager);
mViewPager.setCurrentItem(1);
}
}
FragmentPagerAdapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
private Fragment[] fragments;
private static final String[] CONTENT = new String[] { "frag A","frag B", "frag C" };
// Reference : https://bitbucket.org/owentech/abstabsviewpager/downloads
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
this.fragments = new Fragment[] { new FragmentA(),
new FragmentB(),
new FragmentC()};
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return this.fragments[arg0];
}
public CharSequence getPageTitle(int position) {
return CONTENT[position];
}
#Override
public int getCount() {
return this.fragments.length;
}
}
FragmentX :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentA extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmenta, container, false);
return v;
}
}
main xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/titles"
android:theme="#style/Theme.PageIndicatorDefaults"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.viewpagertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock" >
<activity
android:name="com.example.viewpagertest.MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.PageIndicatorDefaults" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Related

View pager and ImageView not showing android

I got a problem. When im using a pagerView everything inside is showing up beside ImageView.
I'm using this :
<!-- activity_screen_slide.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:id="#+id/relativeLayout">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="0dp" />
</RelativeLayout>
and this :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/common_google_signin_btn_icon_dark" />
</LinearLayout>
And i use this for fragment
package com.example.gebruiker.drumio.SlideScreenTrackPreview;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.gebruiker.drumio.R;
public class TestFragment extends Fragment {
ImageView hihat;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)
inflater.inflate(R.layout.track_preview_test,container,false);
hihat =(ImageView)rootView.findViewById(R.id.imageView2);
hihat.setBackgroundColor(Color.BLACK);
hihat.setColorFilter(Color.BLACK);
return rootView;
}
}
Except the button, nothing is showing up.
Here is the code for the activity that i use :
package com.example.gebruiker.drumio.SlideScreenTrackPreview;
public class ScreenSliderActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setBackgroundColor(Color.WHITE);
mPagerAdapter = new
ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new TestFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
Your activity works for me if you inherit from AppCompatActivity instead of from FragmentActivity. I don't know why; maybe somebody with more experience can elucidate.

ViewPager not showing up in xml and not working in emulator?

I have an application where I have a part of the screen for displaying information about a student and the remaining part with tablayout and viewpager. My problem is tablayout shows up in the design editor but viewpager doesn't. In-spite of the code written nothing is showing up. Tell me where I am getting things wrong?
CAMarksFragment.java
package com.learn.app;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CAMarksFragment extends Fragment {
TabLayout tabLayout;
ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_camarks, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("CA Marks");
viewPager=(ViewPager)getActivity().findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapter(getActivity().getSupportFragmentManager(),getActivity().getApplicationContext()));
tabLayout=(TabLayout)getActivity().findViewById(R.id.tabLayout);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("AppStatus", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("Home", false);
editor.commit();
}
private class CustomAdapter extends FragmentPagerAdapter {
private String[] fragments={"Theory","Practical"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new Theory();
case 1:
return new Practical();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
}
fragments_camarks.xml
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.learn.app.TestTimeTableFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/tablebackgrounds"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ca_all"
android:background="#drawable/allbackgrounds"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/user_profile_photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:background="#drawable/profile_circular_border_imageview"
android:padding="20dp"
android:scaleType="centerCrop"
android:src="#drawable/defaultpic" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Hewitt"
android:textStyle="bold"
android:textColor="#ffffff"
android:id="#+id/camarks_name"
android:padding="10dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:id="#+id/camarks_dept"
android:text="Master of Computer Application"
android:textColor="#ffffff"
android:padding="10dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:id="#+id/camarks_rollno"
android:text="15mx13"
android:textColor="#ffffff"
android:padding="10dp"
/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#ffffff"
android:textStyle="bold"
android:background="#80000000"
android:id="#+id/ca_title"
android:text="CA Marks"
android:gravity="center"
android:padding="10dp"
/>
</LinearLayout>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabLayout"
android:layout_below="#id/ca_all"
android:background="#color/colorPrimaryDark"
app:tabGravity="fill"
app:tabMode="fixed"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/viewPager"
android:layout_below="#id/tabLayout"
android:layout_centerHorizontal="true"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
</ScrollView>
</FrameLayout>
Practical.java
package com.learn.app;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Practical extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_layout1, container, false);
}
}
Theory.java
package com.learn.app;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Theory extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}
fragment_layout contains linearlayout with a textview in it.
In the emulator viewpager doesn't showup and tablayout remain untouchable.What I am getting wrong here. Help me to proceed further. Thanks in advance.
Emulator Output
Many things are wrong in the code.
in xml : add android:layout_height="match_parent" for viewpager
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabLayout"
android:layout_centerHorizontal="true">
in code:
change your code as: you need to use fragment's view to get the viewpager instance. Also your code missing some basic functionalities for viewpager with tablayout
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_camarks, container, false);
viewPager=(ViewPager)view.findViewById(R.id.viewPager);
tabLayout=(TabLayout)view.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Theory"));
tabLayout.addTab(tabLayout.newTab().setText("Practical"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager.setAdapter(new CustomAdapter(getActivity().getSupportFragmentManager(),getActivity().getApplicationContext()));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
tabLayout.setupWithViewPager(viewPager);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("CA Marks");
}
It could be because you are using views from androidx
Well it does have ViewPager along with ViewPager2
Add the following line in build.gradle(:app) file:
implementation 'androidx.viewpager:viewpager:1.0.0'

how can i switch other fragment layout programmatically in Android?

I' ve got two layouts (layout_first.xml and layout_second.xml).
I want to show layout_second, after click a Button (Show Second) in layout_first. And get an EditText value in the layout_first to set EditText value in the layout_second programmaticaly. How can i do this? Thanks for your answers.
my codes:
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/custom_tab_layout_height"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
layout_first.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:focusable="true"
android:background="#bc8383"
android:id="#+id/content_frame">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Second"
android:id="#+id/btnShowSecond"
android:layout_weight="0.18" />
<EditText
android:id="#+id/et1"
android:text="et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:elegantTextHeight="false"
android:maxLength="20"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#85b27e"
android:textSize="40dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:layout_marginTop="10dp"
android:layout_weight="1" />
</LinearLayout>
layout_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:focusable="true"
android:background="#bc8383">
<EditText
android:id="#+id/et2"
android:text="et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:elegantTextHeight="false"
android:maxLength="20"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#85b27e"
android:textSize="40dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn2"
android:id="#+id/btn2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab"
android:textColor="#color/colorAccent"
android:textSize="14dp"
android:gravity="center"
android:fontFamily="#string/font_fontFamily_medium"/>
MainActivity.java
package xmaxsoft.delfragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("One");
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("Two");
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new First(), "One");
adapter.addFrag(new Second(), "Two");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Second.java
package xmaxsoft.delfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class Second extends Fragment {
public Second() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.layout_second, container, false);
String data = getArguments().getString("value");
et2.setText(data);
return view;
}
}
First.java
package xmaxsoft.delfragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class First extends Fragment {
public First() {
}
Button btnShowSecond;
EditText et1;
public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.aid1, fragment, tag);
ft.commitAllowingStateLoss();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.layout_first, container, false);
btnShowSecond = (Button) view.findViewById(R.id.btnShowSecond);
et1 = (EditText) view.findViewById(R.id.et1);
btnShowSecond.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//what kind of code must be here ???
//what kind of code must be here ???
//what kind of code must be here ???
Second myfragment = new Second();
Bundle bundle = new Bundle();
bundle.putString("value",et1.getText().toString());
myfragment.setArguments(bundle);
Activity.addFragment(myfragment, false,"Second");//error ??? cannot resolve method ???
}
});
return view;
}
}
How can i display or switch layout_second programmatically in layout_first? Thank you for your helps.
You can do this by using Intent class.
1. on First.java put this code in clicklistener
public void mybutton_click()
{
Second myfragment = new Second();
Bundle bundle = new Bundle();
bundle.putString("value",et1.getText());
myfragment.setArguments(bundle);
activity.addFragment(myfragment, false,
"Second");
}
To call other Fragment
public void addFragment(Fragment fragment, boolean addToBackStack,
String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment, tag);
ft.commitAllowingStateLoss();
}
In Second.java put this on Oncreate():
String data = getArguments().getString("value");
et2.setText(data);

Page viewer not swiping between views

SO after looking at the samples from viewpagerindicator I realised that they are all in fragment form.
I wanted to do this without fragments which I tried to do but after it compiles it displays the first layout but does not swipe to the other views.
I was looking at the "SampleIconsDefault.java" (from the samples) and made my own and thought I had it right but I have no idea why it doesn't swipe.
The activity & adaptor:
package russellrargill.work.burghcoffeehouseapp;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
//variables for the pager
ViewPager thePager;
IconPageIndicator theIconPageIndicator;
MyPagerAdapter theAdapter;
private Context cxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
//set the context
cxt = this;
theAdapter = new MyPagerAdapter();
thePager = (ViewPager)findViewById(R.id.the_pager);
thePager.setAdapter(theAdapter);
theIconPageIndicator = (IconPageIndicator)findViewById(R.id.icon_page_indicator);
theIconPageIndicator.setViewPager(thePager);
}//END onCreate()
class MyPagerAdapter extends PagerAdapter implements IconPagerAdapter {
String[] titles = new String[]{"Home","Menu","Stores","About Us","Contact"};
protected final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
R.drawable.perm_group_location
};
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater)cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.home_layout, null);
collection.addView(layout,0);
//TODO add layouts for each page
layout = inflater.inflate(R.layout.pagelayoot, null);
collection.addView(layout,1);
layout = inflater.inflate(R.layout.page2layoot, null);
collection.addView(layout,2);
return layout;
}
private int mCount = titles.length;
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position % titles.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return (arg0==arg1);
}
}
}//END CLASS
The main xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|top"
android:background="#000000"
android:clickable="true"
android:focusableInTouchMode="false"
android:padding="1dp"
tools:context=".HomeScreen" >
<LinearLayout
android:id="#+id/nav_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusableInTouchMode="true"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<com.viewpagerindicator.IconPageIndicator
android:id="#+id/icon_page_indicator"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<android.support.v4.view.ViewPager
android:id="#+id/the_pager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nav_layout" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="banana\nbabababba\newfewfewfg\nwefewf"
android:textColor="#FFFFFF"
/>
</LinearLayout>
</ScrollView>
the other 2 layouts (almost identical so I'll only post one)
<?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/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:text="TEST"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_toLeftOf="#+id/textView4"
android:text="A"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_toLeftOf="#+id/textView3"
android:text="IS"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="98dp"
android:layout_toLeftOf="#+id/textView2"
android:text="THIS"
android:textAppearance="?android:attr/textAppearanceLarge" />
Ignore some of the messiness of it all, it was slightly rushed.
Any assistance as to why it doesn't scroll would be greatly appreciated.
one of the fragments......these have to be independant for each fragment you create.......and make a note that my adapter may be different from yours i made a change in the adapter so that i don't have to use the "context" thing again and again...
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentPlaylists extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b, container, false);
}
}
i am building an app right now which does the same thing....but it has many things extra you would have to sort it out...would you like the code for that?
code for the adapter
package sourcecode.jazzplayer;
import java.util.List;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
private static String[] titles = new String[] {"Songs", "My Playlists", "Artists","Albums"};
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public String getPageTitle( int position )
{
return titles[ position ];
}
}
code for the activity that creates the fragments
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MyMusic extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymusic);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentSongs.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentArtists.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentPlaylists.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentAlbums.class.getName()));
ViewPagerAdapter adapter = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(4);
pager.setCurrentItem(0);
}
}

how to keep tabs visible on every activity

I am very new to android programming and I am trying to implement tabs using fragments.
I am using this Tutorial. Everything goes fine but my problem is that I want to open a new activity and on this new activity I want to keep tab bar. I want tab bar visible on every new activity which opens inside tab. I have following code..
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout theLayout = (LinearLayout) inflater.inflate(
R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button) theLayout.findViewById(R.id.btn_startActivity);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(),
"open new activity with tab bar", Toast.LENGTH_LONG).show();
//Here I want to start new activity with tab bar
}
});
return theLayout;
// return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout,
// container, false);
}
}
Here is Main Activity.
package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.sample.fragments.R;
public class FragmentTabs extends SherlockFragmentActivity implements FragmentChangeListener
{
private TabHost mTabHost;
private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private View tabIndicator1;
private View tabIndicator2;
private View tabIndicator3;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mContainerId=R.id.realtabcontent;
fragmentManager = getSupportFragmentManager();
tabIndicator1 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
tabIndicator2 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
tabIndicator3 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
TextView tv1=(TextView)tabIndicator1.findViewById(R.id.txt);
TextView tv2=(TextView)tabIndicator2.findViewById(R.id.txt);
TextView tv3=(TextView)tabIndicator3.findViewById(R.id.txt);
tv1.setText("Tab1");
tv2.setText("Tab2");
tv3.setText("Tab3");
mTabHost.addTab(mTabHost.newTabSpec("1")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator1)
);
mTabHost.addTab(mTabHost.newTabSpec("2")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator2)
);
mTabHost.addTab(mTabHost.newTabSpec("3")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator3)
);
mTabHost.setOnTabChangedListener(new OnTabChangeListener()
{
#Override
public void onTabChanged(String selectedTabID)
{
int tabIndex=Integer.valueOf(selectedTabID);
switch(tabIndex)
{
case 1:
selectedTabID= tabIndicator1.getTag()==null?"Fragment1":tabIndicator1.getTag().toString();
break;
case 2:
selectedTabID= tabIndicator2.getTag()==null?"Fragment2":tabIndicator2.getTag().toString();
break;
case 3:
selectedTabID= tabIndicator3.getTag()==null?"Fragment3":tabIndicator3.getTag().toString();
break;
};
Fragment fragment=fragmentManager.findFragmentByTag(selectedTabID);
if(fragment==null)
{
fragment=getFragment(selectedTabID);
}
replaceFragment(fragment,selectedTabID);
}
});
renderDefaultTab();
}
public void clickMe(final View view)
{
Fragment fragment=new AnotherFragment();
replaceFragment(fragment,"AnotherFragment");
}
#Override
public void replaceFragment(final Fragment fragment, final String tag)
{
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment,tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
public void renderDefaultTab()
{
Fragment fragment=getFragment("Fragment1");
replaceFragment(fragment,"Fragment1");
}
public Fragment getFragment(final String tag)
{
Fragment fragment=null;
if(tag.equalsIgnoreCase("Fragment1"))
fragment=new Fragment1();
else if(tag.equalsIgnoreCase("Fragment2"))
fragment=new Fragment2();
else if(tag.equalsIgnoreCase("Fragment3"))
fragment=new Fragment3();
return fragment;
}
#Override
public void addToTab1Navigation(final String tag)
{
tabIndicator1.setTag(tag);
}
#Override
public void addToTab2Navigation(final String tag)
{
tabIndicator2.setTag(tag);
}
#Override
public void addToTab3Navigation(final String tag)
{
tabIndicator3.setTag(tag);
}
#Override
public void onBackPressed()
{
String name=fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1).getName();
Fragment fragment=fragmentManager.findFragmentByTag(name);
if(fragment instanceof BaseFragment){
String tag=((BaseFragment)fragment).getPreceddingFragmentTag();
if(tag.equalsIgnoreCase("exit"))
System.exit(0);
else
{
fragment=fragmentManager.findFragmentByTag(tag);
replaceFragment(fragment, tag);
}
}
}
}
and layout of this MainActivity.
<?xml version="1.0" encoding="utf-8"?>
<TabHost
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">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+android:id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_gravity="bottom"/>
</LinearLayout>
</TabHost>
Fragment1:
package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment1 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment1";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment1, container, false);
return view;
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
CustomAdapter adapt=new CustomAdapter(getActivity(),0);
ListView lv=(ListView)view.findViewById(R.id.mylistview);
lv.setAdapter(adapt);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(final AdapterView<?> arg0, final View arg1, final int position, final long arg3)
{
Fragment fr=new CustomFragment();
Bundle bundle=new Bundle();
bundle.putString("response", "Option "+(position+1));
fr.setArguments(bundle);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr,"CustomFragment");
}
});
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
Fragment2:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment2 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment2";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment2, container, false);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab2Navigation(this.toString());
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
Fragment3:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment3 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment3";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment3, container, false);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab3Navigation(this.toString());
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
FragmentChangeListener Interface.
package com.example.tabs;
import android.support.v4.app.Fragment;
public interface FragmentChangeListener
{
public void replaceFragment(final Fragment fragment, final String tag);
public void addToTab1Navigation(String tag);
public void addToTab2Navigation(String tag);
public void addToTab3Navigation(String tag);
}
DummyTabFactory:
package com.example.tabs;
import android.content.Context;
import android.view.View;
import android.widget.TabHost;
class DummyTabFactory implements TabHost.TabContentFactory
{
private final Context mContext;
public DummyTabFactory(final Context context)
{
mContext = context;
}
#Override
public View createTabContent(final String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
CustomFragemnt:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.sample.fragments.R;
public class CustomFragment extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "CustomFragment";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
View view=inflater.inflate(R.layout.custom_fragment, container, false);
TextView tv=(TextView)view.findViewById(R.id.response);
tv.setText("You Clicked "+getArguments().getString("response"));
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "Fragment1";
}
}
CustomAdapter:
package com.example.tabs;
import com.actionbarsherlock.sample.fragments.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.Activity;
public class CustomAdapter extends ArrayAdapter<String>
{
Context mcontext;
public CustomAdapter(final Context context, final int textViewResourceId)
{
super(context, textViewResourceId);
mcontext=context;
}
#Override
public int getCount()
{
return 50;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent)
{
View row;
if(convertView==null)
{
LayoutInflater inflater = ((Activity)mcontext).getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
}
else
{
row=convertView;
}
TextView tv=(TextView)row.findViewById(R.id.textView1);
tv.setText("Option "+(position+1));
return row;
}
}
BaseFragment:
package com.example.tabs;
import com.actionbarsherlock.app.SherlockFragment;
public abstract class BaseFragment extends SherlockFragment
{
public abstract String getPreceddingFragmentTag();
}
AnotherFragment:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class AnotherFragment extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
View view=inflater.inflate(R.layout.another_fragment, container, false);
return view;
}
#Override
public String toString()
{
return "AnotherFragment";
}
#Override
public String getPreceddingFragmentTag()
{
return "CustomFragment";
}
}
Layout for AnotherFragment.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/another"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Layout for CustomFragment:
*<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/response"
android:text="#string/another_fragment"
android:onClick="clickMe" />
</RelativeLayout>*
Layout for Frament1:
<?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="vertical">
<ListView
android:id="#+id/mylistview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Layout for Fragment2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/some_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Layout for Fragment3:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/icon"
android:contentDescription="#string/desc" />
</RelativeLayout>
Layout for Row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:padding="5dp" />
</RelativeLayout>
Tab.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity"
android:layout_margin="3dp"
android:background="#drawable/two_state_button"
android:layout_weight="1">
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_compose_inverse"
android:layout_centerHorizontal="true"
android:contentDescription="#string/desc"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/img"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android"></menu>
My suggestion is you should you fragments instead on using new activity. Fragment will be displayed withing your current activity and you don't need to take care about tabs.
but if your need is to use Activity then Create tabhost in newActivity layout as well as you made in this Activity's Layout.
and while creating intent of another activity, send the current Tab number in extras to new Activity.
Intent i = new Intent(Activity.this, NewActivity.Class);
i.putIntExtra("CurrentVisibleTab", currentTabIndex);
startActivity(i).
In New Activity.
tabHost.setDefault(getIntent().getIntExtra("CurrentVisibleTab"));
Hope this will helpful.

Categories

Resources