Android: Switching activities in swipeable tab layout - java

In my android app there is a swipeable tab layout. It has two tabs: New Complain and Previous Complains. When click the complain tab I need to start NewComplain.java. Here is my NewComplain class code segment:
NewComplain class
public class NewComplain extends SherlockFragmentActivity implements View.OnClickListener {
private int Year;
private int Month;
private int Day;
private static final int DATE_DIALOG_ID = 1;
private View viewLoad;
private TextView heading, date;
private Spinner spiComplain, spiProduct;
private EditText description, contInfo;
private Button btnDate;
private ArrayAdapter<String> complainAdapter, prodAdapter;
private ArrayList<String> lstComplain = new ArrayList<String>();
private ArrayList<String> lstProdNames = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
viewLoad = LayoutInflater.from(NewComplain.this).inflate(
R.layout.new_complain, null);
setContentView(viewLoad);
}
}
This id my TabsPagerAdapter class.
package xont.virtusel.v4.controller.sale;
import android.content.Intent;
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);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
case 1:
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
And this is my main activity class.
package xont.virtusel.v4.controller.sale;
import xont.virtusel.v4.controller.R;
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 CustomerComplainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "New Complain", "Previous Complains" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setDisplayShowTitleEnabled(false);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
How should I add switching activity statements into this TabsPagerAdapter class. I used intent. But it's not worked.
Can anyone plz be so kind enough to clarify this issue.
Thanx in advance

What exactly is your problem?
If you can't start new Fragment, try this:
in TabsPagerAdapter in public Fragment getItem() method
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new NewComplain();
case 1:
//return some other class
}
return null;
}
and create a constructor for NewComplain class

You are adding fragments, not activities. In your Tab listeners, you are given a FragmentTransaction which you should be using to update which of your fragments is showing with respect to the tab pressed.
Also, don't inflate in fragment on create, do that in on create view.

Related

Update Tab fragment TextViews during runtime

I have been researching how to accomplish an activity with tabs and have gotten very close to completion. Unfortunately, I have hit a bit of a roadblock.
After following a great guide, I created an interactive activity with a tabLayout and a ViewPager to display the fragment.
Each tab displays the same layout, which is a column of TextViews on the left which keep their default value, and another column of TextViews that need to get their value from different locations.
As a test, I had each tab send different text values to their respective TextViews (example Tab #1 was assigned to use "Downstairs", #2 was assigned to use "Upstairs") - which is accomplished through the onTabSelected listener.
The issue I am running in to, is when the text is assigned to the TextViews. It never displays when the tab is selected. It sometimes displays on the next tab I open. It also sometimes displays Tab 1 assignment values in Tab 3 after I had already opened tab 2 before opening tab 3.
Every other TextView I have worked with updates right away when I use setText(). However, I am very new to using Tab Activities, so I very well could be messing something up.
Distribution.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class Distribution extends FragmentActivity {
private Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distribution);
context = this;
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
TabFragment.cream.setText("Downstairs");
TabFragment.freshnessBottles.setText("Downstairs");
TabFragment.soap.setText("Downstairs");
TabFragment.paperCups.setText("Downstairs");
TabFragment.shortStirSticks.setText("Downstairs");
TabFragment.longStirSticks.setText("Downstairs");
TabFragment.cafeRoyale.setText("Downstairs");
TabFragment.hotChocolate.setText("Downstairs");
TabFragment.equal.setText("Downstairs");
TabFragment.sugar.setText("Downstairs");
TabFragment.greenTea.setText("Downstairs");
TabFragment.orangePekoe.setText("Downstairs");
break;
case 1:
TabFragment.cream.setText("Upstairs");
TabFragment.freshnessBottles.setText("Upstairs");
TabFragment.soap.setText("Upstairs");
TabFragment.paperCups.setText("Upstairs");
TabFragment.shortStirSticks.setText("Upstairs");
TabFragment.longStirSticks.setText("Upstairs");
TabFragment.cafeRoyale.setText("Upstairs");
TabFragment.hotChocolate.setText("Upstairs");
TabFragment.equal.setText("Upstairs");
TabFragment.sugar.setText("Upstairs");
TabFragment.greenTea.setText("Upstairs");
TabFragment.orangePekoe.setText("Upstairs");
break;
case 2:
TabFragment.cream.setText("Shipping");
TabFragment.freshnessBottles.setText("Shipping");
TabFragment.soap.setText("Shipping");
TabFragment.paperCups.setText("Shipping");
TabFragment.shortStirSticks.setText("Shipping");
TabFragment.longStirSticks.setText("Shipping");
TabFragment.cafeRoyale.setText("Shipping");
TabFragment.hotChocolate.setText("Shipping");
TabFragment.equal.setText("Shipping");
TabFragment.sugar.setText("Shipping");
TabFragment.greenTea.setText("Shipping");
TabFragment.orangePekoe.setText("Shipping");
break;
case 3:
TabFragment.cream.setText("Solutions");
TabFragment.freshnessBottles.setText("Solutions");
TabFragment.soap.setText("Solutions");
TabFragment.paperCups.setText("Solutions");
TabFragment.shortStirSticks.setText("Solutions");
TabFragment.longStirSticks.setText("Solutions");
TabFragment.cafeRoyale.setText("Solutions");
TabFragment.hotChocolate.setText("Solutions");
TabFragment.equal.setText("Solutions");
TabFragment.sugar.setText("Solutions");
TabFragment.greenTea.setText("Solutions");
TabFragment.orangePekoe.setText("Solutions");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabFragment.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class TabFragment extends Fragment {
protected static final String ADMIRAL_DOWNSTAIRS_PREFS_NAME = "AdmiralDownstairsPrefsFile";
protected static final String ADMIRAL_UPSTAIRS_PREFS_NAME = "AdmiralUpstairsPrefsFile";
protected static final String ADMIRAL_SHIPPING_PREFS_NAME = "AdmiralShippingPrefsFile";
protected static final String SOLUTIONS_PREFS_NAME = "SolutionsPrefsFile";
protected static SharedPreferences AdmiralDownstairsData;
protected static SharedPreferences AdmiralUpstairsData;
protected static SharedPreferences AdmiralShippingData;
protected static SharedPreferences SolutionsData;
protected static SharedPreferences.Editor editor;
int position;
protected static TextView cream;
protected static TextView freshnessBottles;
protected static TextView soap;
protected static TextView paperCups;
protected static TextView shortStirSticks;
protected static TextView longStirSticks;
protected static TextView cafeRoyale;
protected static TextView hotChocolate;
protected static TextView equal;
protected static TextView sugar;
protected static TextView greenTea;
protected static TextView orangePekoe;
public static Fragment getInstance(int position) {
Bundle bundle = new Bundle();
bundle.putInt("pos", position);
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);
return tabFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt("pos");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cream = view.findViewById(R.id.lblCreamValue);
freshnessBottles = view.findViewById(R.id.lblMilkValue);
soap = view.findViewById(R.id.lblSoapValue);
paperCups = view.findViewById(R.id.lblCupValue);
shortStirSticks = view.findViewById(R.id.lbl4_5StirValue);
longStirSticks = view.findViewById(R.id.lbl7StirValue);
cafeRoyale = view.findViewById(R.id.lblCafeRoyaleValue);
hotChocolate = view.findViewById(R.id.lblHotChocValue);
equal = view.findViewById(R.id.lblEqualValue);
sugar = view.findViewById(R.id.lblSugarValue);
greenTea = view.findViewById(R.id.lblGreenTeaValue);
orangePekoe = view.findViewById(R.id.lblOrangePekoeValue);
}
}
ViewPagerAdapter.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class ViewPagerAdapter extends FragmentPagerAdapter {
private String title[] = {"Admiral - Downstairs", "Admiral - Upstairs", "Admiral - Shipping", "Solutions"};
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return TabFragment.getInstance(position);
}
#Override
public int getCount() {
return title.length;
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
I was attempting to design it in a way that uses SharedPreferences to store and read persistent data. There is a specific sharedPrefs files for each corresponding tab. You will notice that sharedPrefs have not been implemented, and is that way as I wanted to test with just basic setText.

ListFragment and Fragment

I have three tabs in my app. First and third are just fragments and second is a listfragment. But I'm getting the below error when referencing listfragment in main class.
Error:
Type mismatch: cannot convert from ItemFragment to Fragment
Code: mainactivity.java
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.FragmentTransaction;
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.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements TabListener {
ViewPager viewpager;
ActionBar actionbar;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_main);
actionbar=getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewpager=(ViewPager) findViewById(R.id.pager);
viewpager.setAdapter(new MyAdapter(getSupportFragmentManager()));
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
}
});
ActionBar.Tab tab1=actionbar.newTab();
tab1.setText("Home");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionbar.newTab();
tab2.setText("Tracker");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionbar.newTab();
tab3.setText("Progress");
tab3.setTabListener(this);
actionbar.addTab(tab1);
actionbar.addTab(tab2);
actionbar.addTab(tab3);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
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 Fragment_Home();
}
if(arg0==1){
fragment=new ItemFragment();
}
if(arg0==2){
fragment=new Fragment_Progress();
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
Code: TestFragment.java
/**
* A fragment representing a list of Items.
* <p />
* <p />
* Activities containing this fragment MUST implement the {#link Callbacks}
* interface.
*/
public class TestFragment extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TestFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1,
DummyContent.ITEMS));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener
.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated to
* the activity and potentially other fragments contained in that activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
EDIT: Put it as instance....getting the same error.
if(arg0==1){
String param1;
String param2;
fragment=ItemFragment.newInstance(param1, param2);
}
ItemFragment must be an instance of Fragment

Can't access outer class from fragment class android

When I try to access outer class with this code:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
it says:
The method getActivity() is undefined for the tyoe Logger
No enclosing instance of the type Logger is accessible in scope
Here is my Logger.java:
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
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.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageSwitcher;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class Logger extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
static boolean isBoxOpen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logger);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle("Sosyaaal");
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));
Thread connectivity = new Thread(){
public void run(){
try {
while(true)
{
while(!isBoxOpen)
{
if( !isOnline() )
{
isBoxOpen = true;
// display error
runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(Logger.this)
.setTitle("Bağlantı Sorunu")
.setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
.setCancelable(false)
.setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Logger.isBoxOpen = false;// Try Again
}
})
.show();
}
});
}
}
}
} catch (Exception e) {
}
}
};
connectivity.start();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logger, menu);
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Giriş fragment activity
return new GirisFragment();
case 1:
// Kayıt fragment activity
return new KayitFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GirisFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public GirisFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_giris,
container, false);
return rootView;
}
}
public static class KayitFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private ImageSwitcher cinsiyetSwitcher;
public KayitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kayit,
container, false);
cinsiyetSwitcher = (ImageSwitcher) getView().findViewById(R.id.cinsiyetSwitcher);
cinsiyetSwitcher.setFactory(new ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return myView;
}
});
return rootView;
}
}
}
*EDIT*
Changing this line:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
to this:
ImageView myView = new ImageView((Logger)getActivity().getApplicationContext());
solved the problem, but that was not what I was looking for. Thanks to Kapil Vij for correct Answer!
Do this
ImageView myView = new ImageView(getActivity());
getActivity() method is accessible in fragment class, and u r trying to access it using FragmentActivity class instance.
change to:
Logger.this.getApplicationContext()
Logger it-self is activity you call getActivity to get the reference of the activity inside a Fragment
EDIT
Saw that you are calling it inside a fragment change you code to:
ImageView myView = new ImageView(KayitFragment.this.getActivity().getApplicationContext());

Adding tabs below the action bar

In my android application I have implemented a tab layout with swipeable views. Here is my MainActivity class:
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 CustomerComplainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "New Complain", "Previous Complains" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setDisplayHomeAsUpEnabled(false);
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));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
And this is my TabPager Adapter class:
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);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new NewComplain();
case 1:
return new PreviousComplains();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
This is my activity_main.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=".AdminMainActivity" >
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#800000"
android:paddingBottom="4dp"
android:paddingTop="5dp"
android:textColor="#fff"
android:textSize="18dp" />
This works, but the problem is the tabs are adding into the actiob bar as following.
But I want to add these tabs below the action bar. I would be much appreciated if anyone plz be so kind enough to explain how can I solve this problem.
Thanx in advance
I have same issue. I found the solution by replacing this line
actionBar.setHomeButtonEnabled(false);
with
actionBar.setDisplayShowHomeEnabled(true);
and your problem is solved.

Changing Fragments inside FrameLayout and Tabbed Navigation not Working

I am trying to have a tabbed navigation set up in the action bar. When you tap a tab, the frameLayout should change to one of 4 possible fragments in that activity.
However, it's stuck in the first Fragment and when i tap the tabs, nothing happens. Any ideas on what might be wrong? I suspect I am doing something wrong in terms of handling the listener for the tabs, but I can't figure it out (very frustrating). Any help? Thanks in advance.
Form.java (main application)
package com.example.ehistory;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
#SuppressLint("NewApi")
public class Form extends FragmentActivity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form1);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
Tab tab = actionBar.newTab()
//.setText(R.string.anamnesis)
.setIcon(R.drawable.id)
.setTabListener(new TabListener<Frag1>(
this, "anamnesis", Frag1.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
//.setText(R.string.symptom)
.setIcon(R.drawable.current)
.setTabListener(new TabListener<Frag2>(
this, "symptom", Frag2.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
//.setText(R.string.otherhistory)
.setIcon(R.drawable.past)
.setTabListener(new TabListener<Frag3>(
this, "otherhistory", Frag3.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
//.setText(R.string.ros)
.setIcon(R.drawable.ros)
.setTabListener(new TabListener<Frag4>(
this, "ros", Frag4.class));
actionBar.addTab(tab);
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
Frag1 firstFragment = new Frag1();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
#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 boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//don't forget are you sure you don't want to save bullshit
case R.id.newpatient:
Intent intent = new Intent(Form.this, Form.class);
Form.this.startActivity(intent);
default: break;
}
return true;
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(R.id.fragment_container, mFragment, mTag);
ft.commit();
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
#Override
public void onTabReselected(Tab arg0,
android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab arg0,
android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
}
Frag1.java (one of the fragments)
package com.example.ehistory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Spinner;
public class Frag1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_form, container, false);
Spinner spinner = (Spinner) v.findViewById(R.id.gender_spin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.genders, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
AutoCompleteTextView textView = (AutoCompleteTextView) v.findViewById(R.id.ethnicity_edit);
String[] ethnicities = getResources().getStringArray(R.array.ethnicity_array);
ArrayAdapter<String> adapter_auto =
new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, ethnicities);
textView.setAdapter(adapter_auto);
AutoCompleteTextView textView1 = (AutoCompleteTextView) v.findViewById(R.id.nationality_edit);
String[] nationalities = getResources().getStringArray(R.array.nationality_array);
ArrayAdapter<String> adapter_auto1 =
new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, nationalities);
textView1.setAdapter(adapter_auto1);
Spinner spinner1 = (Spinner) v.findViewById(R.id.leg_spin);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this.getActivity(),
R.array.legal_status, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
AutoCompleteTextView textView2 = (AutoCompleteTextView) v.findViewById(R.id.religion_edit);
String[] religions = getResources().getStringArray(R.array.religions);
ArrayAdapter<String> adapter_auto2 =
new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, religions);
textView2.setAdapter(adapter_auto2);
return v;
}
}
Why not use a ViewPager that navigates with tabs? The Android Developer site has an excellent tutorial on Creating Swipe Views with Tabs.

Categories

Resources