I get an error whenever I run the app with the setOnClickListener method. Otherwise it works fine. Can you guys please help me?
package com.grozav.meetmeup;
import com.grozav.meetmeup.R;
import com.grozav.meetmeup.library.UserFunctions;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.Button;
public class DashboardActivity extends FragmentActivity implements TabListener {
UserFunctions userFunctions;
ViewPager viewPager;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
userFunctions = new UserFunctions();
if (!userFunctions.isUserLoggedIn(getApplicationContext())) {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageSelected(int arg0) {
actionBar.setSelectedNavigationItem(arg0);
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabA = actionBar.newTab();
tabA.setText("My Profile");
tabA.setTabListener(this);
ActionBar.Tab tabB = actionBar.newTab();
tabB.setText("Meet Me Up");
tabB.setTabListener(this);
actionBar.addTab(tabA);
actionBar.addTab(tabB);
/*********************************
I GET THE ERROR HERE
*********************************/
Button logout = (Button) findViewById(R.id.btnLogout);
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(getApplicationContext(), LoginActivity.class); // fix View.getContext() to getContext()
startActivity(myIntent); // change to startActivity
}
});
}
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
viewPager.setCurrentItem(arg0.getPosition());
}
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new FragmentA();
}
if (arg0 == 1) {
fragment = new FragmentB();
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
}
dashboard.xml file
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DashboardActivity" />
fragment_a.xml file
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".FragmentA" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Logout" />
</LinearLayout>
</FrameLayout>
This is my first android project so please don't be too harsh. Your help is greatly appreciated! Thank you very much!
You need to write your UI events within according fragment, try this,
public class FragmentA extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_a.xml, null);
Button logout = (Button)view.findViewById(R.id.btnLogout);
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(getActivity(), LoginActivity.class);
startActivity(myIntent); // change to startActivity
}
});
return view;
}
}
try this..
logout.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getApplicationContext(), LoginActivity.class); // fix View.getContext() to getContext()
startActivity(myIntent); /
}});
If you still face problem then change the button id in XML and try again.
Related
EDIT: This is the tutorial I followed, along with it's corresponding youtube video:
http://easyway2in.blogspot.ae/2014/10/android-swipe-views-with-tabs.html
https://www.youtube.com/watch?v=Xu2yoIqTsj4
this is my first experience with using tabs in my android application and i seem to have encountered an error that i cant seem to fix.
Here is the error:
10-29 21:46:50.928 27935-27935/tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta, PID: 27935
java.lang.NullPointerException
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:394)
at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:389)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:832)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1048)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:550)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:509)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:490)
at tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta.MainActivity.onTabSelected(MainActivity.java:61)
at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:577)
at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1105)
at com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:547)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
and here is my main class
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener{
ActionBar actionbar;
ViewPager viewpager;
FragmentPageAdapter ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpager = (ViewPager) findViewById(R.id.pager);
ft = new FragmentPageAdapter(getSupportFragmentManager());
actionbar = getActionBar();
viewpager.setAdapter(ft);
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.addTab(actionbar.newTab().setText("Add Medication").setTabListener(this));
actionbar.addTab(actionbar.newTab().setText("View Medication").setTabListener(this));
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
actionbar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
My Main Activity XML:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
my FragmentPageAdapter class:
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new AddMedFragment();
case 1:
return new ViewMedFragment();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
and an example of one of the displayed fragments (They are the exact same for now) :
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
/**
* Created by WindowsSucks on 10/29/2014.
*/
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AddMedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.add_med_layout, container,false);
}
}
as well as its corresponding XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="Welcome to Add Med page"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Much thanks guys
I was able to fix this by changing the getCount() method of my FragmentPageAdapter class. It is set to return 3 (as seen above) but should only be set to return 2 as that is the number of tabs i currently have setup.
Code:
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new AddMedFragment();
case 1:
return new ViewMedFragment();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
}
How do I get the line in sync with the round ball images and how to change the text and image when clicked ?
I'd like to do something like this:
https://www.behance.net/gallery/13564677/Blog
I got the ListView but I just need help in building the straight line pass through the round ball images.
Thanks for your help!
My Code Follows:
My activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d3d3d3"
>
<FrameLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<ListView
android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:divider="#null"
android:layout_gravity="left"
android:background="#A55676"
>
</ListView>
</android.support.v4.widget.DrawerLayout>
custom_row.xml
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingLeft="35dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="horizontal"
android:background="#drawable/border"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="-5sp"
android:paddingTop="30dp"
/>
<TextView
android:id="#+id/textView1"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="25dp"
android:drawablePadding="20dp"
android:paddingLeft="3dp"
android:paddingTop="25dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff" />
</LinearLayout>
</LinearLayout>
MainActivity.java
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnItemClickListener {
private DrawerLayout drawerLayout;
private ListView listview;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView) findViewById(R.id.drawerList);
drawerLayout=(DrawerLayout)findViewById(R.id.drawerlayout);
MyAdapter myAdapter = new MyAdapter(this);
listview.setAdapter(myAdapter);
drawerLayout.setDrawerShadow(R.drawable.navbar_shadow, Gravity.LEFT);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer,R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View drawerView)
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Drawer Closed", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Drawer Opened", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setIcon(R.color.transparent);
listview.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
public void selectItem(int position)
{// TODO Auto-generated method stub
listview.setItemChecked(position, true);
//setTitle(planets[position]);
}
public void setTitle(String title)
{
getActionBar().setTitle(title);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(drawerListener.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{ // TODO Auto-generated method stub
ImageView titleImageView = (ImageView)view.findViewById(R.id.imageView1);
TextView titleTextView = (TextView)view.findViewById(R.id.textView1);
switch(position)
{
case 0:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState()){
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 1:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 2:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 3:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
Intent intent = new Intent(getApplicationContext(),Featured.class);
startActivity(intent);
break;
case 4:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 5:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
default:
break;
}
}
}
class MyAdapter extends BaseAdapter
{
String[] socialSites;
int [] images = {R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new};
Context context;
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
socialSites = context.getResources().getStringArray(R.array.social);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return socialSites.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return socialSites[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_row,parent, false);
}
else
{
row=convertView;
}
TextView titleTextView = (TextView) row.findViewById(R.id.textView1);
ImageView titleImageView = (ImageView) row.findViewById(R.id.imageView1);
titleTextView.setText(socialSites[position]);
titleImageView.setImageResource(images[position]);
return row;
}
}
Use a ListView, and assign a 9-patch drawable to each item's background which will consist of a centered dot and the vertical line.
The whole trick will be to specify the strechable regions of your nine-patch properly (stretch the line and not the dot).
Once you are happy with that, just make a different dot appearance for the active element and use an XML selector drawable to assign either the default or activated state 9 patch to the background.
I am developing an android Application ,In which i am using FragmentTabHost, I am maintaining a container for each tab, But i am getting problem to reload Tabcontent when i reclick on tabs.
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import com.eDeftsoft.FragmentsContainer.AboutContainerFragment;
import com.eDeftsoft.FragmentsContainer.BaseContainerFragment;
import com.eDeftsoft.FragmentsContainer.CityContainerFragment;
import com.eDeftsoft.FragmentsContainer.HomeContainerFragment;
import com.eDeftsoft.FragmentsContainer.PhotosContainerFragment;
import com.eDeftsoft.Utility.CommonDialogues;
public class HomeScreen extends FragmentActivity {
private static final String TAB_1_TAG = "Home";
private static final String TAB_2_TAG = "Photos";
private static final String TAB_3_TAG = "City";
private static final String TAB_4_TAG = "About";
private FragmentTabHost mTabHost;
TabWidget tbwidget;
HomeContainerFragment homeFragment;
PhotosContainerFragment photosFragment;
CityContainerFragment cityFragment;
AboutContainerFragment aboutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
initView();
homeFragment = new HomeContainerFragment();
photosFragment = new PhotosContainerFragment();
cityFragment = new CityContainerFragment();
aboutFragment = new AboutContainerFragment();
}
private void initView() {
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(setMyCustomIndicator(this, TAB_1_TAG, "Home"),
HomeContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_2_TAG, "Photos"),
PhotosContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_3_TAG, "City"),
CityContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_4_TAG, "About"),
AboutContainerFragment.class, null);
setTabHostColors();
mTabHost.setCurrentTabByTag("TAB_1_TAG");
mTabHost.setCurrentTab(0);
mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
mTabHost.getTabWidget().setStripEnabled(false);
tbwidget = mTabHost.getTabWidget();
/*I had Also used This But getting error when i reclick on sametabs*/
// mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
//
// #Override
// public void onTabChanged(String tabId) {
// // TODO Auto-generated method stub
// if (tabId.equals(TAB_1_TAG)) {
// pushFragments(TAB_1_TAG, homeFragment);
// } else if (tabId.equals(TAB_2_TAG)) {
// pushFragments(TAB_1_TAG, photosFragment);
//
// } else if (tabId.equals(TAB_3_TAG)) {
// pushFragments(TAB_1_TAG, cityFragment);
// } else {
// pushFragments(TAB_1_TAG, aboutFragment);
// }
//
// }
// });
}
/*
* insert the fragment into the FrameLayout
*/
// public void pushFragments(String tag, Fragment class1) {
//
// FragmentManager manager = getSupportFragmentManager();
// FragmentTransaction ft = manager.beginTransaction();
//
// ft.replace(R.id.realtabcontent, class1);
// ft.commit();
// }
public TabSpec setMyCustomIndicator(Context con, String tag,
String labeltext) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, null, false);
((TextView) tabIndicator.findViewById(R.id.title)).setText(labeltext);
// ((ImageView) tabIndicator.findViewById(R.id.icon))
// .setImageResource(resid);
return spec.setIndicator(tabIndicator);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
FragmentManager fm = getSupportFragmentManager();
if (currentTabTag.equals(TAB_1_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_1_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_1_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_2_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_2_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_2_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_3_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_3_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_3_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_4_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_4_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_4_TAG)).popFragment();
}
if (!isPopFragment) {
CommonDialogues.showAlertDialog(HomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
}
}
private void setTabHostColors() {
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.TRANSPARENT);
final TextView tv = (TextView) mTabHost.getTabWidget()
.getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(12);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTabHost = null;
}
}
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
Any help will be appreciated. I had gone through some of tutorials and coderepository but couldn`t found solution to my problem.
How Can i reload The content Of First tab when first tab is clicked again.
I had asked a question
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
I searched a lot and come to the conclusion , We can implement OnTabChangeListner and when any tab is clicked again we can reset it.(I was having need to reload tab when it is clicked 2nd time)
<!--Layout for Tabs -->
<?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" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<!-- android:background="#drawable/footer" -->
<FrameLayout
android:id="#+id/tabframeLayout"
android:layout_width="fill_parent"
android:layout_height="#dimen/tabframe_height"
android:layout_marginTop="1dp"
android:background="#FBFAFA" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="#dimen/tab_height"
android:background="#F2F0F0" >
</TabWidget>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.abc.Fragments.FragmentA;
import com.abc.Fragments.FragmentA1;
import com.abc.Fragments.FragmentA2;
import com.abc.Fragments.FragmentA3;
import com.abc.Utility.CommonDialogues;
public class MyHomeScreen extends FragmentActivity implements
OnTabChangeListener {
private TabHost tabHost;
private String currentSelectedTab;
private HashMap<String, ArrayList<Fragment>> hMapTabs;
final int TEXT_ID = 100;
final String arrTabLabel[] = { "FragmentA", "FragmentA1", "FragmentA2",
"FragmentA3" };
final static int arrIcons[] = { R.drawable.homee, R.drawable.photoi,
R.drawable.cityi, R.drawable.abouti };
private MyTabView arrTabs[] = new MyTabView[4];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_home_screen);
hMapTabs = new HashMap<String, ArrayList<Fragment>>();
hMapTabs.put(AppConstant.TAB_1_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_2_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_3_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_4_TAG, new ArrayList<Fragment>());
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
tabHost.setup();
TabHost.TabSpec spec = tabHost.newTabSpec(AppConstant.TAB_1_TAG);
tabHost.setCurrentTab(0);
arrTabs[0] = new MyTabView(this, 0, arrTabLabel[0]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[0]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_2_TAG);
arrTabs[1] = new MyTabView(this, 1, arrTabLabel[1]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[1]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_3_TAG);
arrTabs[2] = new MyTabView(this, 2, arrTabLabel[2]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[2]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_4_TAG);
arrTabs[3] = new MyTabView(this, 3, arrTabLabel[3]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[3]);
tabHost.addTab(spec);
// set background for Selected Tab
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID);
// tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
// iv.setBackgroundResource(R.color.green);
// Listner for Tab 1//
tabHost.getTabWidget().getChildAt(0)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(0)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_1_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.setCurrentTab(0);
}
}
});
/* Listner for Tab 2 */
tabHost.getTabWidget().getChildAt(1)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(1)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_2_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(1);
tabHost.setCurrentTab(1);
}
}
});
/* Listner for Tab 3 */
tabHost.getTabWidget().getChildAt(2)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(2)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_3_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(2);
tabHost.setCurrentTab(2);
}
}
});
/* Listner for Tab 4 */
tabHost.getTabWidget().getChildAt(3)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(3)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_4_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(3);
tabHost.setCurrentTab(3);
}
}
});
}
/* Method for adding fragment */
public void addFragments(String tabName, Fragment fragment,
boolean animate, boolean add) {
if (add) {
hMapTabs.get(tabName).add(fragment);
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.animator.slide_in_right,
R.animator.slide_out_left);
}
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
/* Method for remove fragment */
public void removeFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(
hMapTabs.get(currentSelectedTab).size() - 2);
hMapTabs.get(currentSelectedTab).remove(
hMapTabs.get(currentSelectedTab).size() - 1);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
// reset frgment used when clicked on same tab
private void resetFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(0);
hMapTabs.get(currentSelectedTab).clear();
hMapTabs.get(currentSelectedTab).add(fragment);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
#Override
public void onBackPressed() {
if (hMapTabs.get(currentSelectedTab).size() <= 1) {
// super.onBackPressed();
CommonDialogues.showAlertDialog(MyHomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
} else {
removeFragment();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (hMapTabs.get(currentSelectedTab).size() == 0) {
return;
}
hMapTabs.get(currentSelectedTab)
.get(hMapTabs.get(currentSelectedTab).size() - 1)
.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onTabChanged(String tabName) {
// TODO Auto-generated method stub
currentSelectedTab = tabName;
// make iteration for unselected tab and make normal background
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
.findViewById(TEXT_ID);
tv.setTextColor(Color.parseColor("#BDBDBD"));
View iv = (View) tabHost.getTabWidget().getChildAt(i);
iv.setBackgroundColor(0x00000000);
}
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID); // for Selected Tab
tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
if (hMapTabs.get(tabName).size() == 0) {
if (tabName.equals(AppConstant.TAB_1_TAG)) {
addFragments(tabName, new FragmentA(), false, true);
} else if (tabName.equals(AppConstant.TAB_2_TAG)) {
addFragments(tabName, new FragmentA1(), false, true);
} else if (tabName.equals(AppConstant.TAB_3_TAG)) {
addFragments(tabName, new FragmentA2(), false, true);
} else if (tabName.equals(AppConstant.TAB_4_TAG)) {
addFragments(tabName, new FragmentA3(), false, true);
}
} else {
addFragments(
tabName,
hMapTabs.get(tabName).get(hMapTabs.get(tabName).size() - 1),
false, false);
}
switch (tabHost.getCurrentTab()) {
case 0:
// we can also set background color of tabview
// iv.setBackgroundResource(R.color.green);
break;
case 1:
// iv.setBackgroundResource(R.color.red);
break;
case 2:
// iv.setBackgroundResource(R.color.yellow);
break;
case 3:
// iv.setBackgroundResource(R.color.twitter);
break;
}
}
private class MyTabView extends LinearLayout {
int nIdx = -1;
TextView tv;
public MyTabView(Context c, int drawableIdx, String label) {
super(c);
ImageView iv = new ImageView(c);
nIdx = drawableIdx;
// used for forground icons//
iv.setImageResource(arrIcons[nIdx]);
tv = new TextView(c);
tv.setText(label);
tv.setGravity(Gravity.BOTTOM);
tv.setTextSize(14.0f);
tv.setTypeface(null, Typeface.BOLD);
tv.setId(TEXT_ID);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.9f);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.3f);
layout.setMargins(0, 3, 0, 0);
iv.setLayoutParams(layout);
layout.setMargins(0, 3, 0, 2);
tv.setLayoutParams(param);
tv.setTextColor(Color.parseColor("#BDBDBD"));
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
addView(iv);
addView(tv);
}
}
}
<!--Layout for FragmenA -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TAB 1 FIRST SCREEN"
android:textColor="#color/dark_blue"
android:textSize="30sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="Go to Next Screen" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
</EditText>
</LinearLayout>
code for fragment A ...it is extend By Basefragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstScreen extends BaseFragment implements OnClickListener {
private Button btnNext;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "I am in onCreate", Toast.LENGTH_LONG).show();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_firstscreen,
container, false);
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
System.out.println("replace");
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragmentTabActivity.addFragments(Const.TAB_FIRST,
new SecondScreen(), true, true);
}
}
Code for BaseFragment is
extend this class with all sub fragment which you are going to add on (While adding fragment use myhomescreenActivity(This object) and call add Function in MyHomeScreen ):
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class BaseFragment extends Fragment {
protected MyHomeScreen myhomescreenActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myhomescreenActivity = (MyHomeScreen) this.getActivity();
}
public boolean onBackPressed() {
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
This is the link of repository on Github for further understanding.......
https://github.com/thankimanish/TabUsingFragment
1.You can try moving your code inside the onCreate method to the onResume method so that every time fragment comes to front the code inside the onResume gets executed and reloads the frament.
2.You can also try overriding the onHiddenChanged method of the fragment and reload the fragment as soon as fragment becomes visible
//I am using action bar tabs in my app,I want to switch from one activity to another activity with in tabs when I press on tabs,how can I call the activity with in tabs. I want to display any activity with in actionbar tabs.
public class MainActivity extends Activity implements TabListener {
// Refresh menu item
private MenuItem action_search;
Tab tab1, tab2, tab3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//creating tabs
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//adding tabs to actionbar
tab1 = actionBar.newTab();
tab1.setText("camera");
tab1.setTabListener(this);
actionBar.addTab(tab1);
tab2 = actionBar.newTab();
tab2.setText("contacts");
tab2.setTabListener(this);
actionBar.addTab(tab2);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
switch (tab.getPosition()) {
case 0:
Intent i = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(i);
break;
case 1:
Intent i = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(i);
break;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
MainActivity.java
package com.example.moviesswipe;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.Menu;
#SuppressWarnings("unused")
#SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "English", "Tamil", "Hindi" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_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) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
TabsPagerAdapter.java
package com.example.moviesswipe;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new English();
case 1:
return new Tamil();
case 2:
return new Hindi();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
Here i placed three tabs , for each tab i created three activity.
English.java , Tamil.java and Hindi.java
sample one:
package com.example.moviesswipe;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
#SuppressWarnings("unused")
public class English extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.english, container, false);
return rootView;
}
}
For each class you need to create a layout:
No need to entry these classes in your manifest coz these are all fragments.
Try it like this dude :) Happy coding :)
Say if there any queries.
I am getting an error that I have not been able to figure out after weeks of trying.
I am trying to do an example of a fragment that opens another dialog fragment when i click a button.
The dialog fragment has an edittext view that i am trying to use to enter a name and then when i click ok the fragment is suppose to use an interface to complete a callback to the calling fragment and then to take the text from the edittext and use it to update the text in a textview in the first fragment's layout, but no matter what i do it will not work.
I have run out of ideas of what is wrong and how to fix it. any help would be greatly appreciated.
the compiler says line 72 gives the error in DialogFragment (NullPointerException)
(I put a // line 72 comment on that line)
mListener.setsNewUsername(etEnteredName.getText().toString());// line 72
main activity
package com.example.fragments;
import android.os.Bundle;
import android.app.Activity;
import android.app.DialogFragment;
import android.widget.TextView;
public class FragmentsActivity extends Activity
implements SignInDialogFragment.MyDialogListener{
String sNewUsername = new String("[Enter Username]");
public void setsNewUsername(String sNewUsername) {
this.sNewUsername = sNewUsername;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
TextView textViewFrag1 =(TextView)dialog.getActivity().findViewById(R.id.textViewFragment1);
textViewFrag1.setText("Hello" + sNewUsername);
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
}
}
main fragment
package com.example.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.d("Fragment 1", "onCreateView");
return inflater.inflate(R.layout.fragment1, container,false);
}
public void onAttach(Activity activity){
super.onAttach(activity);
Log.d("Fragment 1", "onAttach");
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d("Fragment 1", "onCreate");
}
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
Log.d("Fragment 1", "onActivityCreated");
}
public void onStart(){
super.onStart();
Button btnShowSignin = (Button)getActivity().findViewById(R.id.btnShowSignInDialog);
btnShowSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignInDialogFragment signinDialog = new SignInDialogFragment();
signinDialog.show(getFragmentManager(), null);
}
});
Log.d("Fragment 1", "onStart");
}
public void onResume(){
super.onResume();
Log.d("Fragment 1", "onResume");
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d("Fragment 1", "onPause");
}
public void onStop(){
super.onStop();
Log.d("Fragment 1", "onStop");
}
public void onDestroyView(){
super.onDestroyView();
Log.d("Fragment 1", "onDestroyView");
}
public void onDestroy(){
super.onDestroy();
Log.d("Fragment 1", "onDestroy");
}
public void onDetach(){
super.onDetach();
Log.d("Fragment 1", "onDetach");
}
}
dialog fragment
package com.example.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class SignInDialogFragment extends DialogFragment {
View dialogView;
EditText etEnteredName;
String enteredUserName = new String("My Name");
public String getEnteredUserName() {
return enteredUserName;
}
public void setEnteredUserName(String enteredUserName) {
this.enteredUserName = enteredUserName;
}
public interface MyDialogListener {
public void setsNewUsername(String string);
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
MyDialogListener mListener;
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (MyDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return super.onCreateView(inflater, container, savedInstanceState);
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.signin, null))
.setPositiveButton("SignIn", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
etEnteredName = (EditText)getActivity().findViewById(R.id.username);
mListener.setsNewUsername(etEnteredName.getText().toString()); // line 72
mListener.onDialogPositiveClick(SignInDialogFragment.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
#Override
public void dismiss() {
// TODO Auto-generated method stub
super.dismiss();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
super.onDismiss(dialog);
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
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="horizontal">
<fragment
android:name="com.example.fragments.Fragment1"
android:id="#+id/fragment1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
/>
</LinearLayout>
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00FF00">
<TextView
android:id="#+id/textViewFragment1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SignIn Dialog Text Here"
android:textColor="#000000"
android:textSize="25sp"
/>
<Button
android:id="#+id/btnShowSignInDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show SignIn Dialog"
android:textColor="#000000"
android:onClick="onClick"
/>
</LinearLayout>
signin.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
/>
</LinearLayout>
Change this
etEnteredName = (EditText)getActivity().findViewById(R.id.username);
to
View v = inflater.inflate(R.layout.signin,null);
etEnteredName = (EditText)v.findViewById(R.id.username);
You need to use the inflated view object to initialize your EditText. EditText is in R.layout.signin. findViewById looks for a view with the id mentioned in the current inflated layout.
Declare View v; as a instance variable.
Then
v = inflater.inflate(R.layout.signin,null);
builder.setView(v);
Then
etEnteredName = (EditText)v.findViewById(R.id.username);