Android Fixed Tabs on a Processing PApplet - android

I am developing an Android app based on Processing
I would like to show two Fixed Tabs with some content when Menu Button is pressed.
Tab1 would contain some settings and maybe a Help Button
Tab2 should have a ListView to show a list of presets.
Now I am trying to create two TextViews for sake of simplicity.
I am trying with the approach of the Ketai library for KetaiList
So there's an inner class that extends TabHost inside the PApplet class extended by my application:
public class MyProcessingApp extends PApplet {
public void setup() {
}
public void draw() {
}
public void keyPressed() {
if (key == CODED) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
TabHost th = new GBTab(this);
}
}
}
public class GBTab extends TabHost {
private PApplet parent;
TabHost self;
TabWidget tab1, tab2;
LinearLayout layout;
public GBTab(PApplet _parent) {
super(_parent.getApplicationContext());
parent = _parent;
init();
}
public void init() {
println("GBTab init");
self = this;
layout = new LinearLayout(parent);
TabSpec settingsSpec = self.newTabSpec("SETTINGS").setContent(
new TabContentFactory() {
public View createTabContent(String tag) {
TextView tv = new TextView(parent);
tv.setText("SETTINGS!");
return tv;
}
}
)
.setIndicator("SETTINGS");
self.addTab(settingsSpec);
TabSpec presetsSpec = self.newTabSpec("PRESETS").setContent(
new TabContentFactory() {
public View createTabContent(String tag) {
TextView tv = new TextView(parent);
tv.setText("PRESETS!");
return tv;
}
}
)
.setIndicator("PRESETS");
self.addTab(presetsSpec);
self.setCurrentTab(0);
parent.runOnUiThread(new Runnable() {
public void run() {
parent.addContentView(self, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
}
}
);
}
}
}
This code gives a NullPointerException when adding a tab to the TabHost.
self.addTab(settingsSpec);
since self is null.
Is this a valid approach?
Thank you

How about the second answer (24 votes) in this? Essentially it says that since you are not using a tabactivity you need to call self.setup(); before adding any tabs

Related

How can I implement OnClickListener of an ImageView in a fragment?

Can anyone kindly help me implement the opening of a new activity upon clicking of an ImageView. I have a code snippet displayed below.
public class TabFan extends Fragment {
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.tab_fan, container, false);
// Onclick Listening
ImageView image = (ImageView) findViewById(R.id.image);
image.setOnClickListener(this);
}
public void onClick(View v) {
// Launching new Activity on hitting the image
Intent j = new Intent(getApplicationContext(), Activity2.class);
startActivity(j);
// End intent
}
}
Ok I have a code with three tabs, the following controls my tabs which is working right.
public class Fans extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fans);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Fans"));
tabLayout.addTab(tabLayout.newTab().setText("Jersey"));
tabLayout.addTab(tabLayout.newTab().setText("Team"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
}
#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) {
}
}
I have another class pager
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
TabFan tab1 = new TabFan();
return tab1;
case 1:
TabJersey tab2 = new TabJersey();
return tab2;
case 2:
TabTeam tab3 = new TabTeam();
return tab3;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Finally the interested raw class TabFan, now where exactly should that listener be implemented. I have tried the class Fans but apparently am getting some crush, TabFan seem not to work with the events too. Any help please.
public class TabFan extends Fragment {
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.tab_fan, container, false);
// Onclick Listener
}
}
With the code that you have provided, you will need to do two things to properly link the image object to the onClick() method that you have written.
First, the Fragment class needs to implement the View.OnClickListener interface. This is what makes the onClick(View v)actually activate on a click when using setOnClickListener(this). Replace your class declaration line with:
public class TabFan extends Fragment implements View.OnClickListener {
Second, if you are going to add any more clickable objects to TabFan with setOnClickListener(this), then onClick(View v) needs to verify that it is dealing with the expected View:
#Override
public void onClick(View v) {
if (v.getId() == R.id.image) {
// Launching new Activity on hitting the image
Intent j = new Intent(getActivity().getApplicationContext(), Activity2.class);
startActivity(j);
// End intent
}
}
If you click Ctrl + Space keys, Android Studio will show you suggestion window and generate overriding methods like onClick for you.
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(getActivity(), Activity2.class);
startActivity(j);
}
});
Doesn't matter where you are, in Fragment or in Activity. ImageView just needs View.OnClickListener. for detecting click events override onClick method.
And another point when you need any context in fragment use getActivity() or getActivity().getApplicationContext()
What I like to do is setting up the onClick in the XML already like this:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="yourMethod"
android:src="#drawable/yourpicture"/>
Then in your Fragment or Activity just implement yourMethod to open the new Activity:
public void yourMethod(View v) {
Intent intent = new Intent(this, ToOpenAcitivy.class);
startActivity(intent);
}
Also this site helped me a lot when learning about stuff like this.

Keep fragments info between activities

I have my main activity actionbaractivity One where you can screenslide through some fragmets, on each fragment you have an imageView and a ListView where you can click any item and the image will change. Also in the menu options you have a button where you change to an almost exact activity: actiobbaractivity Two which also have this button to change to activity One
What I'm able to do is to keep the image when sliding the fragments, but unable to keep the fragments state's through the change of activities.
For example
I'm in activity One on fragment 3 with the image: "something". I click on the button to change to activity Two, I do things here and then, I click on the button to change to activity One and I want to see my fragment 3 with the image: "something" and not the default fragment 1 and default image
Im using ActionBarActivity, FragmentStatePagerAdapter and Fragment for each activity
Thanks for the help
According to the Activity and Fragment lifecycles (http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle and http://developer.android.com/guide/components/fragments.html#Lifecycle), the most reliable way of persisting states between activity/fragment changes is to use the default API for saving and restoring states:
When the activity/fragment is being dismissed (either because of a configuration change such as screen rotation or because the user requested to go to another activity/fragment), you can save its state in a Bundle object. When it is being created, you can restore its saved state, thus recreating a new instance exactly like the one the user left - so the user feels nothing has changed. This does not depend on the specific subclass of activity/fragment you are using.
I have implemented something like what you want: in my case, a fragment containing a menu with buttons that would each lead the user to another fragment containing a submenu with a "back" button. So if the user went from menu to submenu 1, then back to menu, then to submenu 2, then back to menu and finally again to submenu 1, I wanted that submenu 1 to appear just like the user has left it in the first time.
For that I have created:
1) an interface defining my submenu types, implemented by my activities so they could change between my submenus
2) a master generic class, which all my submenus would extend, that had a Bundle object to store their state
3) in my activities, I had an array of Bundle capable of storing one instance of each of my submenus (because I am only interested in restoring the last state, so I don't need more than one)
The interface (item 1):
public interface SubmenusManager {
public static enum Submenus {
ROOTMENU,
SUBMENU1,
SUBMENU2;
private static final int size = Submenus.values().length;
public static int size() {
return size;
}
public static int getId(Submenus test) {
switch(test) {
case SUBMENU1:
return 1;
case SUBMENU2:
return 2;
case ROOTMENU:
default:
return 0;
}
}
}
public void cloneCurrentSubmenuState(Parcelable toOverwrite);
public Bundle getLastStoredSubmenuState(Submenus submenu);
public void setCurrentSubmenuTo(Submenus submenu);
}
The generic class (item 2):
public class MenuFragment extends Fragment {
private Bundle menuData = new Bundle();
public static String RESTORE_MAIN_OBJECT = "restore_main";
public Bundle getMenuData() {
return menuData;
}
public Bundle cloneMenuData() {
return new Bundle(menuData);
}
public void setMenuData(Bundle menuData) {
this.menuData = menuData;
}
}
One of the activities (item 3):
public class ExampleAct extends FragmentActivity implements SubmenusManager {
/**
* instance variables
*/
private MenuFragment mMenu;
private Bundle [] menuData; // the Array of Bundles!
private static final String CONTAINER = "parcelable_container";
private static final String SUBMENU = "saved_submenu";
private Submenus curSubmenu = Submenus.ROOTMENU; // the default state is the ROOTMENU
private boolean restoreLastSavedState = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) { // first time creating this activity
menuData = new Bundle[Submenus.size()];
} else { // this activity has a saved state from before
// restore all the data from all the submenus
menuData = (Bundle[]) savedInstanceState.getParcelableArray(CONTAINER);
// restore the info about which is the current active submenu
curSubmenu = (Submenus) savedInstanceState.getSerializable(SUBMENU);
}
buildMenuFragment(true);
//(...) stuff
}
private void buildMenuFragment(boolean restoreState) {
// (re)builds fragment inside menu.
// restoreState flags whether activity should look for
// saved state data and restore it
restoreLastSavedState = restoreState;
switch(curSubmenu) {
// Eclipse warns you about which are the constants in your enum
case ROOTMENU:
mMenu = new FragmentRootMenu();
break;
case SUBMENU1:
mMenu = new FragmentSubmenu1();
break;
case SUBMENU2:
mMenu = new FragmentSubmenu2();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, mMenu)
.commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(SUBMENU, curSubmenu);
cloneCurrentSubmenuState(mMenu.getMenuData().
getParcelable(MenuFragment.RESTORE_MAIN_OBJECT));
outState.putParcelableArray(CONTAINER, menuData);
// (...) stuff
}
#Override
public void cloneCurrentSubmenuState(Parcelable toOverwrite) {
if (menuData == null) menuData = new Bundle[Submenus.size()];
if (toOverwrite != null)
mMenu.getMenuData().putParcelable(MenuFragment.RESTORE_MAIN_OBJECT, toOverwrite);
menuData[Submenus.getId(curSubmenu)] = mMenu.cloneMenuData();
}
#Override
public Bundle getLastStoredSubmenuState(Submenus forThisSubmenu) {
return
(menuData == null || !restoreLastSavedState) ? new Bundle() : menuData[Submenus.getId(forThisSubmenu)];
}
#Override
public void setCurrentSubmenuTo(Submenus toThisSubmenu) {
if (mMenu != null) {
cloneCurrentSubmenuState(mMenu.getMenuData().
getParcelable(MenuFragment.RESTORE_MAIN_OBJECT));
}
curSubmenu = toThisSubmenu;
buildMenuFragment(true);
}
One of the submenus (extension of item 2):
public class FragmentSubmenu1 extends MenuFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_submenu1, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
// (...) stuff
MyParcelableObject tmp = null; // MyParcelableObject is a class
// that implements Parcelable and stores
// relevant info to rebuild this menu
// from a saved state
SubmenusManager m = (SubmenusManager) getActivity(); // remember activity implements SubmenusManager
Bundle bnd = m.getLastStoredSubmenuState(SubmenusManager.Submenus.SUBMENU1);
if (bnd != null) tmp = bnd.getParcelable(MenuFragment.RESTORE_MAIN_OBJECT);
if (tmp == null) {
tmp = new MyParcelableObject();
tmp.buildFromScratch(); // initializes with default data
}
// back button
Button backToMainMenu = (Button) getView().findViewById(R.id.submenu1_back);
backToMainMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((SubmenusManager) getActivity()).
setCurrentSubmenuTo(SubmenusManager.Submenus.ROOTMENU);
}
});
// (...) stuff
}
}
The Root menu (extension of item 2):
public class FragmentRootMenu extends MenuFragment {
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_rootmenu, null);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
Button btnSubmenu1 = (Button) myView.findViewById(R.id.btn_call_submenu1);
btnSubmenu1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((SubmenusManager) getActivity()).
setCurrentSubmenuTo(SubmenusManager.Submenus.SUBMENU1);
}
});
Button btnSubmenu2 = (Button) myView.findViewById(R.id.btn_call_submenu2);
btnSubmenu2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((SubmenusManager) getActivity()).
setCurrentSubmenuTo(SubmenusManager.Submenus.SUBMENU2);
}
});
}
}
For that to work between activities, all you need to do is pass that object that stores the last state of all fragments (in my case, that would be Bundle [] menuData) to the activity that is being called through its Intent; you would recover it the same way as my ExampleAct did in its onCreate(). You could also wrap that Bundle [] inside a custom Parcelable object (very similar to my example MyParcelableObject; inside that one I had stuff like HashMap) if using an array is a problem.
Here how to pass a Parcelable between activities:
How to send an object from one Android Activity to another using Intents?

Replacing a Fragment: Previous view remains Active in the background?

I am working on an application where I have to change the view of one tab when tab is changed. I am doing it following way using OnTabChangedListener. I am able to replace view. But when I change my tab to some other tab, previous view remain tapable in the background? Why is it so? In front, new view is populated but If I tap anywhere on the screen where previous view's controls were, the functionality is executed. I am not getting where may the problem lie. Please help me out. Thanks!
public class FragmentTabs extends FragmentActivity implements OnTabChangeListener {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fragment_tabs);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.setOnTabChangedListener(this);
if (Database.getSharedObject(getApplicationContext()).getAppSettings().getListView() == 1) {
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("", getResources().getDrawable(R.drawable.home_tab)), HomeFragment.class, null);
} else {
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("", getResources().getDrawable(R.drawable.home_tab)), CalendarViewFragment.class, null);
}
mTabHost.addTab(mTabHost.newTabSpec("groups").setIndicator("", getResources().getDrawable(R.drawable.groups_tab)), GroupFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("templates").setIndicator("", getResources().getDrawable(R.drawable.templates_tab)), TemplateFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("settings").setIndicator("", getResource
mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height = height;
mTabHost.getTabWidget().getChildAt(1).getLayoutParams().height = height;
mTabHost.getTabWidget().getChildAt(2).getLayoutParams().height = height;
mTabHost.getTabWidget().getChildAt(3).getLayoutParams().height = height;
// Database.getSharedObject(getApplicationContext());
mTabHost.setCurrentTab(0);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onTabChanged(String arg0) {
mTabHost.getCurrentTabView().invalidate();
if (mTabHost.getCurrentTab() == 0) {
if (Database.getSharedObject(getApplicationContext()).getAppSettings().getListView() == 1) {
HomeFragment homeFragment = new HomeFragment();
mTabHost.getCurrentTabView().invalidate();
getSupportFragmentManager().beginTransaction().replace(R.id.realtabcontent, homeFragment).addToBackStack(null).commit();
} else {
CalendarViewFragment calendarViewFragment = new CalendarViewFragment();
mTabHost.getCurrentTabView().invalidate();
getSupportFragmentManager().beginTransaction().replace(R.id.realtabcontent, calendarViewFragment).addToBackStack(null).commit();
}
}
}
}
Add android:clickable="true" to your new tab's root layout. It will prevent click events to be passed through the layouts behind.

Change tab color in Android

I have these codes for my two tabs. I would like to change the color but I dont know how to do it. Should it be done in my java file, or in my xml ? Thank You
Here are my codes
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.TabHost;
// This is now the first activity that you see when you enter the app, it derives from TabActivity
public class TabsActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// The activity displays a TabHost layout with a TabWidget below the actual tab contents
setContentView(R.layout.tabs);
// Two tabs are added one displays the main list activity, the other an info activity
addNewTab("Kalender", MainActivity.class);
addNewTab("Info", InfoActivity.class);
}
// This function defines and adds a tab to the interface
private void addNewTab(String name, Class<? extends Activity> activityClass)
{
TabHost tabHost = getTabHost();
// The new tab will display a separate activity, so it needs an intent for it
Intent activityIntent = new Intent().setClass(this, activityClass);
// The TabSpec sets the internal name and the visible name of the newly created tab
TabHost.TabSpec spec = tabHost.newTabSpec(name).setIndicator(name).setContent(activityIntent);
// Finally, the new tab is added to the TabHost
tabHost.addTab(spec);
}
}
Changing text Color and Background color of TAB
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE); //Changing background color of tab
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); /*for Selected Tab changing text color*/
tv.setTextColor(Color.BLACK);
}
This is one way to make the background of a single tab have a color, and also to set one.
tabHost.getTabWidget().getChildAt(tabIndex).setBackgroundColor(color);
If you want to customize the look of your tabs, you should use your own tab widget. The thing is that most android widgets are themed using bitmaps, so you can't simply change the gradient color.
Some people suggest simply changing the backgroundColor of the standard widget, but it is going to look rather flat.
Using your own widget goes something like this:
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
Also have a look at the Android style guide's tab section.
Hey if you want to change the tab color just like in Google Playstore try this:
public class MainActivity extends AppCompatActivity implements TabLayout.BaseOnTabSelectedListener {
private AppBarLayout appBarLayout;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private View mRevealView;
private View mRevealBackgroundView;
private int fromColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appBarLayout = findViewById(R.id.main_appbar);
toolbar = findViewById(R.id.main_toolbar);
tabLayout = findViewById(R.id.main_tablayout);
viewPager = findViewById(R.id.main_viewPager);
mRevealView = findViewById(R.id.reveal);
mRevealBackgroundView = findViewById(R.id.revealBackground);
setUpTabs();
setSupportActionBar(toolbar);
fromColor = R.color.colorTabOne;
}
private void setUpTabs() {
viewPager.setAdapter(new ViewPagerAdapter());
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(this);
tabLayout.getTabAt(0).setText("TAB ONE");
tabLayout.getTabAt(1).setText("TAB TWO");
tabLayout.getTabAt(2).setText("TAB THREE");
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
animateAppAndStatusBar(0, R.color.colorTabOne);
break;
case 1:
animateAppAndStatusBar(appBarLayout.getWidth() / 2, R.color.colorTabTwo);
break;
case 2:
animateAppAndStatusBar(appBarLayout.getWidth(), R.color.colorTabThree);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
private void animateAppAndStatusBar(int cx, final int toColor) {
Animator animator = ViewAnimationUtils.createCircularReveal(
mRevealView,
cx,
appBarLayout.getBottom(), 0,
appBarLayout.getWidth() / 2);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
mRevealView.setBackgroundColor(getResources().getColor(toColor));
}
});
mRevealBackgroundView.setBackgroundColor(getResources().getColor(fromColor));
animator.setStartDelay(200);
animator.setDuration(125);
animator.start();
mRevealView.setVisibility(View.VISIBLE);
fromColor = toColor;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
ViewPagerAdapter() {
super(MainActivity.this.getSupportFragmentManager());
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new TabOneFragment();
case 1:
return new TabTwoFragment();
case 2:
return new TabThreeFragment();
default:
throw new IllegalArgumentException("Invalid position " + i);
}
}
#Override
public int getCount() {
return 3;
}
}
}
You can check out my Github or Youtube tutorial

Problems with OnClickListener for a tab in android

I'm new to android programing and I'm having problems with OnClickListener for tabs in my app. I found on stack a solution how it should be done, but for some reason it's not working.
I'm trying to use the 2nd answer
For some reason I'm getting 2 errors.
First one is on the name on of my activity: The type DragonLords must implement the inherited abstract method View.OnClickListener.onClick(View).
Second one is on the OnClick method: The method onClick(View) of type new View.OnClickListener(){} must override a superclass method.
Here is a part of my code:
public class DragonLords extends TabActivity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Home.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("home").setIndicator("home",
res.getDrawable(R.drawable.hometab))
.setContent(intent);
tabHost.addTab(spec);
getTabWidget().getChildAt(0).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (getTabHost().getCurrentTab()==0) {
getTabHost().setCurrentTab(0);
}else
{
getTabHost().setCurrentTab(0);
}
}
});
After that I'm creating more tabs. With out the onclicklistener it's working, the thing is I need to be able to reload the tabs when they are active.
Anyone have an idea what I'm doing wrong?
I added the necessary imports.
Gatz
You must implement the onClick method not in an anonymous inner class like you have done in your code.
Try using new TabWidget.OnClickListener instead of just the normal OnClickListener
Something akin to the following:
public class TestActivity extends TabActivity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getTabWidget().getChildAt(0).setOnClickListener(new TabWidget.OnClickListener() {
public void onClick(View v) {
if (getTabHost().getCurrentTab()==0) {
getTabHost().setCurrentTab(0);
}else
{
getTabHost().setCurrentTab(0);
}
}
});
}
public void onClick(View theView) {
// Do something with view here
}
}
you are doing it pretty hard way.. i did it like this...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tablayout);
res = getResources();
tabHost=(TabHost)this.findViewById(android.R.id.tabhost);
tabHost.getTabWidget().setDividerDrawable(R.drawable.vertical_seperator);
setupTab(new TextView(this), "Login",new Intent().setClass(this,loginForm.class));
setupTab(new TextView(this), "Can't Login",new Intent().setClass(this,ForgotPwd.class));
setupTab(new TextView(this), "Register",new Intent().setClass(this,RegisterUser.class));
}
private void setupTab(final View view, final String tag,final Intent myIntent)
{
View tabview = createTabView(tabHost.getContext(), tag);
TabSpec setContent = tabHost.newTabSpec(tag).setIndicator(tabview).setContent(
new TabContentFactory()
{
public View createTabContent(String tag)
{return view;}
}).setContent(myIntent);
tabHost.addTab(setContent);
}
private static View createTabView(final Context context, final String text)
{
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
hope this helps....
tabs_bg is just an xml with
<TextView android:id="#+id/tabsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="15dip"
android:textColor="#drawable/tab_text_selector" />

Categories

Resources