Android: Actionbar with ListView and GridView - android

I'm trying to develop an actionbar with three tabs. In the first tab I wanna have a gridview with images and in the other two tabs I wanna have a listview. How can I make this? Is there a code example in the internet? (I haven't find one)

first you need to create TabBar app with Three Tabs then go for List
and Grid view on Tabs.
So I have already created some tutorials to do this.
First Create Three Tabs:
Check this for Tab Bar : TabWidget in Android
For List View: ListView in Android
For Grid View: Grid View Demo With Images
Below is the code how you can create Tabs in Android
ActivityTabWidget.java
package com.rdc;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;
public class ActivityTabWidget extends TabActivity {
private TabHost mTabHost = null;
private Intent ihome, imusic, iabout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//create tab host to add tabs
mTabHost = getTabHost();
LayoutInflater.from(this).inflate(R.layout.main,
mTabHost.getTabContentView(), true);
// create intents to load another page on Tabs
ihome = new Intent(ActivityTabWidget.this, ActivityHome.class);
imusic = new Intent(ActivityTabWidget.this, ActivityMusic.class);
iabout= new Intent(ActivityTabWidget.this,ActivityAboutMe.class);
// create tabs and add to TabHost
mTabHost.addTab(mTabHost.newTabSpec("tab1")
.setIndicator(" Home ")
.setContent(ihome));
mTabHost.addTab(mTabHost.newTabSpec("tab3")
.setIndicator(" Music ")
.setContent(imusic));
mTabHost.addTab(mTabHost.newTabSpec("tab3")
.setIndicator(" About Me ")
.setContent(iabout));
// set default selected tab
mTabHost.setCurrentTab(0);
}
}
Then you need to create Three Activities
ActivityHome.class
ActivityMusic.class
ActivityAboutMe.class
so the output will be like this..

Related

FrameLayout.LayoutParams doesn't work

I am trying to avoid the following situation in the activity( screen shot of the activity). When I add the margins using setMargins it does not work. I have tried adding margins via xml code and the end result is achieved but it very time consuming and it can't be guaranteed that it will work for all devices. How can i do it in code?
Here is the code.
package com.example.android.tourguide;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class TouristAttractions extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_item);
/*
Finding the Toolbar that is defined in activity_main.xml via the id toolbar.
Note:The following three lines should be repeated for all the activities that are opened from the MainActivity. Also the toolbar should have an orientation
which is not zero.
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_for_menu_items);
/*
Setting the action bar as the toolbar defined in the above code line
*/
setSupportActionBar(toolbar);
/*
Setting the title text color of the app bar.
*/
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.color_of_text_of_app_bar));
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
/*
Finding the drawerLayout so that when the user clicks on the menu item of the navigation drawer it should close as we invoke the method closeDrawers()
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.home_menu) {
/*
Opening the home class that is the MainActivity when the Tourist Home menu button is clicked.
*/
Intent intentToOpenHomeClass = new Intent(TouristAttractions.this, MainActivity.class);
startActivity(intentToOpenHomeClass);
} else if (menuItem.getItemId() == R.id.entertainment_menu) {
Intent intentToOpenEntertainmentClass = new Intent(TouristAttractions.this, Entertainment.class);
startActivity(intentToOpenEntertainmentClass);
} else if (menuItem.getItemId() == R.id.gardens_menu) {
Intent intentToOpenGardenClass = new Intent(TouristAttractions.this, Garden.class);
startActivity(intentToOpenGardenClass);
} else {
mDrawerLayout.closeDrawers();
}
return true;
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout_for_menu_items);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager_for_menu_items);
AdapterForFragmentOfTouristAttraction adapterForFragmentOfTouristAttraction = new AdapterForFragmentOfTouristAttraction(this, getSupportFragmentManager());
viewPager.setAdapter(adapterForFragmentOfTouristAttraction);
tabLayout.setupWithViewPager(viewPager);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) toolbar.getLayoutParams();
params.setMargins(0, toolbar.getHeight(), 0, 0);
ActionBar actionbar = getSupportActionBar();
/*
actionBar.setDisplayHomeAsUpEnabled(true) will make the icon clickable and add the < at the left of the icon.
*/
actionbar.setDisplayHomeAsUpEnabled(true);
/*
Enabling the menu icon of the navigation.However note we are simply adding the menu icon however clicking on the icon does absolutely nothing.
*/
actionbar.setHomeAsUpIndicator(R.drawable.baseline_menu_white_24);
}
}
First of all, it might be a better idea to use a LinearLayout with a vertical orientation, a RelativeLayout, or a ConstraintLayout to position views below one another. In more exotic use cases even a CoordinatorLayout might be better suited.
FrameLayouts are mostly used to simply overlay views on one another, without depdendencies between them.
This said, the issue you are facing occurs because you use toolbar.getHeight() right after adding the view, which will always be 0. Try attaching a debugger and see for yourself!
The reason is that Android needs a bit of time to measure -> layout -> draw its views, and if you call getHeight right after adding the layout it will not have done either of those steps, leaving the values uninitialized, at 0.
There are ways around that, but again, you would be better off using a different layout alltogether. If you insist on using a FrameLayout the cleanest approach would be to extend it and create your own, where you can measure and layout the view yourself. The hacky, hard to maintain, and confusing approach would be to use ViewTreeObserver to listen for the changes and react to them. This is bad because you have to wait for a full layout pass before you trigger yet another one.
Don't use a FrameLayout here.
You havn't Done
yourView.setLayoutParams(params);

Tab Fragment Tutorial failing on build

I am working with this tutorial to teach myself tab fragments. When I paste and run the MainActivity I get this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference
at hss.fragmenttabstutorial.MainActivity.onCreate(MainActivity.java:27)
So I changed the Activity to ActionBarActivity, and changed the ActionBar to getSupportActionBar like many suggested. Now it won't build due to getSupportActionBar, stating "Incompatible types". What should I do?
Here's the Main code:
import android.app.Activity;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Fragment;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
// Declaring our tabs and the corresponding fragments.
ActionBar.Tab bmwTab, fordTab, toyotaTab;
Fragment bmwFragmentTab = new FragmentTab1();
Fragment toyotaFragmentTab = new FragmentTab2();
Fragment fordFragmentTab = new FragmentTab3();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Asking for the default ActionBar element that our platform supports.
ActionBar actionBar = getSupportActionBar();
// Screen handling while hiding ActionBar icon.
actionBar.setDisplayShowHomeEnabled(false);
// Screen handling while hiding Actionbar title.
actionBar.setDisplayShowTitleEnabled(false);
// Creating ActionBar tabs.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Setting custom tab icons.
bmwTab = actionBar.newTab().setText("Fragment1");
toyotaTab = actionBar.newTab().setText("Fragment2");
fordTab = actionBar.newTab().setText("Fragment3");
// Setting tab listeners.
bmwTab.setTabListener(new TabListener(bmwFragmentTab));
toyotaTab.setTabListener(new TabListener(toyotaFragmentTab));
fordTab.setTabListener(new TabListener(fordFragmentTab));
// Adding tabs to the ActionBar.
actionBar.addTab(bmwTab);
actionBar.addTab(toyotaTab);
actionBar.addTab(fordTab);
}
}
Instead of import android.app.ActionBar use android.support.v7.app.ActionBar.
This ensures compatibility with the rest of the support library including ActionBarActivity.

How do I use Intent to go to one of five (user selected via tab) activities?

On my main activity I have a tab with 5 choices. I am trying to write in persistence using SharedPreferences to allow the user to select one of the tabs (as well as set a timer), and then those selections are saved so that one of five activities will come up when the "Start" button is pushed. I am trying to write this functionality into an Intent in the onClickListener for the "Start" button, so that it will use the currently selected tab and go to the the activity that goes with that tab. The 5 tabs, all have their own themed activity that they will go to (not by clicking the tab, but rather the "Start" button), so what should my Intent code show in order for this to happen?
I was thinking, the choice of activity should go into the 2nd parameter of the new Intent() part of the code, since that determines which class it goes to (for now I have a "dummy" activity in there, but it should be changed). But since it must be based on what the user selected (whichever tab is currently selected), it should somehow say that, but how? Or is the answer to write an implicit Intent (which, from my limited understanding, allows an Intent to choose from multiple factors in determining the best activity to go to)?
I am not writing in the value to be saved (and passed on) for the timer set up yet, so we just need to focus on the tab selection being saved and passed through an Intent for now. Thanks for your help.
P.S. I'm not quite sure my SharedPreferences code is correct, so suggest changes if you think something is wrong.
NOTE: PLEASE, PLEASE let me know if this question is unclear. This is the 2nd time I've asked it (simplified from the last time) and I'm so far not getting a response. I just really need to know how to go from one tab choice through the Intent to the activity associated with that tab choice (so, one of five choices). How can an Intent allow room for this choice? I MUST use SharedPreferences for other reasons (the timer) but really, this posting is about how to properly write an Intent, so don't get too hung up on the SharedPreferences part. If anyone can attempt an answer, I would be so very, very grateful, thanks you in advance!!
MainSelectorActivity.java
package com.azurespot.disastertimer.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.View;
import android.widget.Button;
import com.azurespot.disastertimer.app.tabs.GodzillaTab;
import com.azurespot.disastertimer.app.tabs.NuclearTab;
import com.azurespot.disastertimer.app.tabs.TsunamiTab;
import com.azurespot.disastertimer.app.tabs.VolcanoTab;
import com.azurespot.disastertimer.app.tabs.ZombieTab;
public class MainSelectorActivity extends FragmentActivity {
Resources resrc;
FragmentTabHost tabHost;
private Button btnStart;
public static final String TABTIMER = "Tab_and_Timer";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_selector);
tabSetUp();
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
MediaActivity.class);
startActivity(i);
}
});
tabAndTimerPersist();
}
public void tabSetUp() {
resrc = getResources();
// TabHost setup & functionality
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//------Zombie tab------
//Creates tab and sets zombie image in view
tabHost.addTab(tabHost.newTabSpec("zombie").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_zombie_selected)),
ZombieTab.class, null);
//------Nuclear tab------
//Creates tab and sets nuclear image in view
tabHost.addTab(tabHost.newTabSpec("nuclear").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_nuclear_selected)),
NuclearTab.class, null);
//------Tsunami tab------
//Creates tab and sets tsunami image in view
tabHost.addTab(tabHost.newTabSpec("tsunami").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_tsunami_selected)),
TsunamiTab.class, null);
//------Godzilla tab------
//Creates tab and sets tsunami image in view
tabHost.addTab(tabHost.newTabSpec("godzilla").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_godzilla_selected)),
GodzillaTab.class, null);
//------Volcano tab------
//Creates tab and sets volcano image in view
tabHost.addTab(tabHost.newTabSpec("volcano").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_volcano_selected)),
VolcanoTab.class, null);
//set Zombie tab as default (zero based)
tabHost.setCurrentTab(0);
}
#Override
protected void onPause() {
super.onPause();
tabAndTimerPersist();
}
private void tabAndTimerPersist() {
SharedPreferences prefs = getSharedPreferences(TABTIMER, MODE_PRIVATE);
tabHost.getCurrentTab();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("zombie", 0);
editor.putInt("nuclear", 0);
editor.putInt("tsunami", 0);
editor.putInt("godzilla", 0);
editor.putInt("volcano", 0);
editor.commit();
}
}
TabHost tabHost;
Intent intent;
TabHost.TabSpec spec;
Resources res;
spec = tabHost.newTabSpec("A")
.setIndicator(getTabView("A","#333333"))
.setContent(new Intent().setClass(this,A.class));
tabHost.addTab(spec);
spec = tabHost
.newTabSpec("B")
.setIndicator(getTabView("B","#ffffff"))
.setContent(new Intent().setClass(this,B.class));
tabHost.addTab(spec);
tabHost.setCurrentTab(1);
setTabColor(tabHost);
//Your on tab change listener call setTabColor(tabHost);
private View getTabView(String text, String color)
{
LayoutInflater inf_manifesto=getLayoutInflater();
View v=inf_manifesto.inflate(R.layout.customt_tab, null);
TextView t = (TextView)v.findViewById(R.id.txt);
t.setText(text);
t.setTextColor(Color.parseColor(color));
return v;
}
public static void setTabColor(TabHost tabhost)
{
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#3d99d1"));
TextView tv1 = (TextView)tabhost.getTabWidget().getChildAt(i).findViewById(R.id.txt);
tv1.setTextColor(Color.parseColor("#ffffff"));
}
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#ffffff")); // selected
TextView tv2 = (TextView)tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).findViewById(R.id.txt);
tv2.setTextColor(Color.parseColor("#333333"));
}
Use this way to create tabs.

Want to show webpage on clicking images in viewpager

I want to show webpage when we click an image in viewpager. Can you please help me in this. Also I want to know if multiple images are there in viewpager so how will I get the respective webpages of them.
Thanks in advance.
**MainActivity.java**
package com.example.viewimage;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// open the desired page
Intent browserIntent = new Intent("android.intent.action.VIEW",
Uri.parse("http://www.craftsvilla.com/anvi-s-classic-nawabi-earrings-studded-with-white-stones-and-emeralds.html"));
startActivity(browserIntent);
}
});
}
}
If you want to show this webpage inside your app, you would have to add a WebView. Set its visibility to View.GONE. Add OnClickListener to your viewPager. On click set the visibility of the webView to be View.VISIBLE. To go back, override the functionality of 'back' key - and on its click hide the webpage.
Or you can open other activity that holds the webView.
You can also open the webpage with android's browser.
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri);
startActivity(browserIntent);
Edited :
Add to your xml before closing your RelativeLayout
<LinearLayout
android:id="#+id/cover_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"/>
instead of 'viewPager.setOnClickListener' write
(findViewById(R.id.cover_layout))

Show tabs in a second bar using Actionbarsherlock

I have a problem showing tabs with ActionBarSherlock. I have copied the example code of actionbarsherlock demos in my own aplication, if I run the application in a 7'' display like Nexus 7, tabs appear at the same bar as the title. But if I run the ABS sample in the same device tabs appears in a different bar.
What's wrong with my application?
Here is my code:
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.internal.ResourcesCompat;
import com.mbal.misseries.R;
public class ProvaDeFragments extends SherlockActivity implements ActionBar.TabListener {
private TextView mSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock_Light); //Used for theme switching in samples
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_navigation);
mSelected = (TextView)findViewById(R.id.text);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i = 1; i <= 3; i++) {
ActionBar.Tab tab = getSupportActionBar().newTab();
tab.setText("Tab " + i);
tab.setTabListener(this);
getSupportActionBar().addTab(tab);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction transaction) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
mSelected.setText("Selected: " + tab.getText());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
}
}
It's shown like this:
From my application
But if I run the sample ABS code appears like this:
ABS Sample Demo
Thanks in advance!
You aren't doing anything wrong, except testing it on a device with enough room. ;-)
Per the ActionBar documentation in the Google developer site:
When you want to provide navigation tabs in an activity, using the
action bar's tabs is a great option (instead of using TabWidget),
because the system adapts the action bar tabs for different screen
sizes—placing them in the main action bar when the screen is
sufficiently wide, or in a separate bar (known as the "stacked action
bar") when the screen is too narrow, as shown in figures 9 and 10.
If you make longer tabs, add more actions to the bar, and/or test it in a thinner view (portrait on a mobile phone, for example), it should break it out to a second bar automatically.
Note the view in their examples (copied below) the second one that stacks them is much more narrow than the first.
Figure 9
Figure 10

Categories

Resources