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
Related
I have a tab swiped layout which includes four tabs each of which have their own layout and fragment, in my main activity layout a viewpager takes part for changing tabs. specific view(tab) loads when app starts up and the others will be loaded when the tab changes. my problem is when I nevigate to the third or forth tab (not the second tab) a new instance of it's corresponding fragment will be created instead of loading previously created fragment (the expected behavior that only occur for the second tab).When I navigate to the second tab (SecondPageFragment()) and again come back to first tab it works correct and doesn't create a new IndexFragment, it load the previously created fragment instead so every thing is fine in this case but when I go to the third or forth tab and then come back to first tab it creates an new instance of IndexFragment.
what's the possible reason for that and why it only happens for third,forth etc tab and only second tab works correct and as expected ????
here is my codes that switch the tabs and their corresponding fragments
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new ForthPageFragment();
case 1:
return new ThirdPageFragment();
case 2:
return new SecondPageFragment();
case 3:
return new IndexFragment();
default :
break;
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
and here is my main activity code :
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "صفحه چهارم","صفحه سوم","صفحه دوم","صفحه اصلی" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager)findViewById(R.id.tabpager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
viewPager.setCurrentItem(3);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
}
viewPager.setOffscreenPageLimit(3);
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.
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
I have implemented an actionbar but its title is not getting displayed. Also my app has two fragments , the title should change as per the fragment displayed.
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupActionBar();
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
public void onPageSelected(int position)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageScrollStateChanged(int state)
{
if (state == ViewPager.SCROLL_STATE_DRAGGING)
{
}
if (state == ViewPager.SCROLL_STATE_IDLE)
{
}
}
});
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new AllPatient();
case 1:
//Intent intent = new Intent(MainActivity.this,abc.class);
return new LaunchpadSectionFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
private void setupActionBar() {
ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM);
ViewGroup v = (ViewGroup)LayoutInflater.from(this)
.inflate(R.layout.header, null);
actionBar.setCustomView(v,
new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.RIGHT));
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(getTitle());
}
}
Please also tell me how to add dividers between the icons in actionbar.
Thanks in advance.
Try changing this line:
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
By this one:
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME, ActionBar.DISPLAY_SHOW_CUSTOM);
Add the show title flag like so
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
I think the problem is that you're adding a custom view with a width of MATCH_PARENT and Android removes the action bar title (but not the home icon) in that case. It's not very logical, but that's the behavior I see in my app. Setting the width to WRAP_CONTENT creates the same problem. The solution is to give the custom view a fixed width, or if you need the width to vary from one activity to another, calculate the width programmatically and set it to a new fixed width for each activity.
This should definitely work
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(title);
I'm wondering how can I work with a listfragment, and at the same time, using an static linearlayout with 4 filter buttons at the top of the list. Here is the problem:
First of all, I use an Action Bar + Tab Navigation from ActionBarSherlock :
QuestList extends FragmentMapActivity implements ActionBar.TabListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getTabs();
}
private void getTabs() {
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getSupportActionBar().newTab();
tab1.setText("Geo");
tab1.setTabListener(this);
getSupportActionBar().addTab(tab1);
ActionBar.Tab tab2 = getSupportActionBar().newTab();
tab2.setText("No Geo");
tab2.setTabListener(this);
getSupportActionBar().addTab(tab2);
}
...
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getText().toString().compareTo("Geo") == 0) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, Map.getInstance()).commit();
}
else {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, List.newInstance(0)).commit();
}
}
I got some problems with the MapView, but I finally fixed all of them. Now the problem is that I want something like this:
Static LinearLayout + ListFragment
List extends ListFragment
...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initializations();
getQuests();
if (gigHash.isEmpty()) {
TextView eList = new TextView(getActivity());
eList.setText(R.string.no_loc_gig_no_items);
eList.setWidth(Gravity.CENTER);
}
else {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mAdapter = new NoLocGigAdapter(getActivity(),R.layout.gig_noloc_row_land,gigList);
}
else {
mAdapter = new NoLocGigAdapter(getActivity(),R.layout.gig_noloc_row,gigList);
}
setListAdapter(mAdapter);
}
}
...
So I'm using my own adapter and I get all my items from a service.
The problem is, doing the transaction, I can only use a fragment, and I have to show the items dinamically with my own ArrayAdapter, so I don't know how to include a part of static code into that view...
Any suggestion? I think that handle with fragments it's a little weird!
PS: At first, I thought that I could call a fragment, and this, calling a static xml within the linearlayout and a ListFragment inside, but I think I can't do this, right?