I use Android Tab Example with two tabs, view pager and fragments (structure on the image):
For get fragments i use the solution from this post.
When my device is rotation i want to display two fragments at the same time.
I the stackoverflow.com/questions/17970021 a similar problem, but I don't know how to apply the solution to my task, because i have TabLayout.
If you know idea, can you help me?
In activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
>
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
</FrameLayout>
In MainActivity.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.annotation.NonNull;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replaceFragment(0);
}
public void replaceFragment(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TabOneFragment();
break;
case 1:
fragment = new TabTwoFragment();
break;
default:
break;
}
if (null != fragment) {
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
in TabOneFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabOneFragment extends Fragment {
private View inflatedView = null;
public TabOneFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_one, container, false);
return this.inflatedView;
}
}
in TabTwoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabTwoFragment extends Fragment {
private View inflatedView = null;
public TabTwoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_two, container, false);
return this.inflatedView;
}
}
Related
I am a beginner, new to android technology. Actually I tried to solve already existing question through different approach. I took 3 fragments in single activity, and in 1st fragment i took editText, in 2nd fragment I took button and after clicking on that button I tried to display the fragment1 data in 3rd fragment By passing value through Bundle and I got stuck. How to do this task by this approach.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/top"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
<FrameLayout
android:id="#+id/mid"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
<FrameLayout
android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
</LinearLayout>
MainActivity
package com.example.com.dynamicfragmentproject;
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Top_fragment frg1=new Top_fragment();
transaction.add(R.id.top,frg1);
transaction.commit();
}
public void cacheData(String str) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Mid_fragment frg2=new Mid_fragment();
transaction.add(R.id.mid,frg2);
transaction.commit();
Bundle bundle = new Bundle();
bundle.putString("editText",str);
frg2.setArguments(bundle);
}
public void cacheData1(String name) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Bottom_fragment frg3=new Bottom_fragment();
transaction.add(R.id.bottom,frg3);
transaction.commit();
Bundle bundle = new Bundle();
bundle.putString("editText",name);
frg3.setArguments(bundle);
}
}
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".Top_fragment">
<!-- TODO: Update blank fragment layout -->
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hello_blank_fragment"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"/>
</RelativeLayout>
Fragment1.java
package com.example.com.dynamicfragmentproject;
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.EditText;
public class Top_fragment extends Fragment {
private EditText editText;
View view;
public Top_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_top_fragment, container, false);
editText = view.findViewById(R.id.editText1);
String str = editText.getText().toString();
MainActivity main = (MainActivity) getActivity();
main.cacheData(str);
return view;
}
}
fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".Mid_fragment">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:layout_centerVertical="true"
android:layout_centerHorizontal="false"
/>
</RelativeLayout>
Fragment2.java
package com.example.com.dynamicfragmentproject;
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.Button;
import android.widget.EditText;
public class Mid_fragment extends Fragment {
private Button buttonSubmit;
View view;
public Mid_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
buttonSubmit = view.findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity main1 = (MainActivity) getActivity();
Bundle bundle = getArguments();
String name = bundle.getString("editText");
main1.cacheData1(name);
}
});
return view;
}
}
fragment3.xml
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/bottom"
tools:context=".Bottom_fragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:padding="10dp"
/>
</FrameLayout>
Fragment3.java
package com.example.com.dynamicfragmentproject;
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.EditText;
import android.widget.TextView;
public class Bottom_fragment extends Fragment {
private TextView viewText;
View view;
public Bottom_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_bottom_fragment, container, false);
viewText = view.findViewById(R.id.textView1);
Bundle bundle = getArguments();
String name = bundle.getString("editText");
viewText.setText(name);
return view;
}
}
In first fragment create a object of second fragment.
FragmentTwo fragmenttwo=new FragementTwo();
Bundle bundle = new Bundle();
bundle.putSerializable(object,"data")
fragmenttwo.setArguments(bundle);
In the second fragment
Bundle bundle = getArguments();
if(bundle != null){
SampleModel model = (SampleModel) bundle.getSerializable("data");
}
You need to change code in MainActivity, you commit() before set args. Change code in whole app like below
public void cacheData(String str) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Mid_fragment frg2=new Mid_fragment();
Bundle bundle = new Bundle();
bundle.putString("editText",str);
frg2.setArguments(bundle);
transaction.add(R.id.mid,frg2);
transaction.commit();
}
And get data on Fragment onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
You can commit a transaction using commit() only prior to the activity saving its state (when the user leaves the activity). If you attempt to commit after that point, an exception is thrown. This is because the state after the commit can be lost if the activity needs to be restored. For situations in which it's okay that you lose the commit, use commitAllowingStateLoss().
For more detail you may refer this link
Updated :
In your code pass bundle value is perfect but when you get string of editext in Mid_fragment
getArguments().getString("editText");
this getting empty that's why solution is you do not need to pass Top fragment value to Mid Fragment just edittext make static like this
change public static EditText editText
Top_fragment extends Fragment {
View view;
public static EditText editText;
}
and Mid_fragment add this
onClick(View v) {
if (Top_fragment.editText!=null)
strtext=Top_fragment.editText.getText().toString();
here is full code of Mid_fragment
public class Mid_fragment extends Fragment {
View view;
private Button buttonSubmit;
public Mid_fragment() {
// Required empty public constructor
}
String strtext="";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
//strtext = getArguments().getString("editText");
buttonSubmit = view.findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Top_fragment.editText!=null)
strtext=Top_fragment.editText.getText().toString();
MainActivity main1 = (MainActivity) getActivity();
main1.cacheData1(strtext);
}
});
return view;
}
}
Iam trying to keep a simple fragment with only one button.But it is coming 2 times like this
I had a linear layout and another nested linear layout in it.These are all present in activity_welcome.xml whose content is as follows :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#99cc00"
android:orientation="vertical"
tools:context="com.acs.AfterLogin.WelcomeActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/replacable_container"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Iam trying to replace the replacable_container(Linear Layout) with the fragment whose java class is this :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.acs.AfterLogin.WelcomeActivity;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeFragment1 extends Fragment{
View v;
CardView cardView1,cardView2,cardView3;
CircleImageView userIcon;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return inflater.inflate(R.layout.welcome_fragment_1,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The xml content of fragment is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e0ebe5"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"/>
</LinearLayout>
The operations like fragment transcation and all are contained in the mainactivity whose java code is this :
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.acs.AfterLogin.WelcomeFragments.WelcomeFragment1;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeActivity extends AppCompatActivity {
FragmentTransaction transaction;
WelcomeFragment1 frag1;
FragmentManager manager;
String imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
(new FragTask()).execute();
}
private class FragTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
transaction = manager.beginTransaction();
frag1 = new WelcomeFragment1();
transaction.replace(R.id.replacable_container, frag1, "welcome_1");
transaction.commit();
return null;
}
}
}
Thanks a lot in advance :)
Try to change this line
v=inflater.inflate(R.layout.welcome_fragment_1,container);
to
v=inflater.inflate(R.layout.welcome_fragment_1,container, false);
And return the inflated view. The boolean value indicates that you don't want to attach your view to container. Check this. Fragment will attach it later by itself.
Please return inflated view instead of inflating again in return statement.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return v;
}
When I click on my Travel button it should replace the Menufragment with the TravelFragment. But for some reason it doesnt work and I dont know if the issue is from the onClicklistener or the way i replace fragments. And when I debug it complains in line 32, "View root = inflater.inflate(R.layout.fragment_menu, container, false);" is the code I have.
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MenuFragment extends Fragment {
public MenuFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_menu, container, false);
Button TravelButton = (Button) root.findViewById(R.id.travel);
TravelButton.setOnClickListener(buttonListener);
return root;
}
private View.OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId() ){
case R.id.travel:{
TravelFragment newFragment = new TravelFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
break;
}
}
};
}
And this is my xml code for my mainactivity (The FrameLayout is inside a RelativeLayout for containing the container where I can replace fragments for example:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
I cant find the problem. Please help. Im new to Android Studio so be patient with me! All help is welcome.
Try using this code by adapting it:
frag_results frag_results = new frag_results();
FragmentManager manager = getActivity().getSupportFragmentManager();
manager.beginTransaction().replace(R.id.framelayout_secundary, frag_results, frag_results.getTag()).commit();
I create a little app with 3 static fragments and a view pager adapter. But what I want is to create Only one kind of fragment and with a button "add" , add other fragment which will be adapted by the view pager.. here is what i have done
FragmentTab1.java ; FragmentTab2 ; FragmentTab3 have the same code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab2.xml
View view = inflater.inflate(R.layout.fragmenttab2, container, false);
return view;
}
}
here is my MainActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
//Button adfg = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "Tab1", "Tab2", "Tab3" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#000000" />
</android.support.v4.view.ViewPager>
fragmenttab1.xml ; fragmenttab2.xml ; fragmenttab3.xml has the same code
<?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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1" />
<Button
android:id="#+id/bajou"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ajouter fragment" />
</LinearLayout>
You need to create a method to add the fragment on the subclass of FragmentPagerAdapter, more or less like this :
//use those lists
private List<Fragment> listFragment = new ArrayList<Fragment>();
private List<String> listFragmentTitle = new ArrayList<String>();
private List<Integer> listFragmentIcon = new ArrayList<Integer>();
public void addTab(Fragment fragment,String title, int icon) {
listFragment.add(fragment);
listFragmentTitle.add(title);
listFragmentIcon.add(icon);
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return listFragment.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listFragment.size();
}
Then you just need to use it on the subclass of Activity, example :
//create a private method to set a new - dynamic fragment in the ACTIVITY
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
Finally, add the fragment (for example, inside an onClickListener) :
//INSIDE an onClickListener
pagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
this is my MainActivity.java class #BlazeTama
package com.light.frag;
import com.light.frag.R;
import com.light.frag.ViewPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
Button ajou = (Button) findViewById(R.id.bajou);
ajou.setOnClickListener(this);
}
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bajou:
ViewPagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
break;
}
}
}
I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
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;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#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 void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<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">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
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:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.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"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.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"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.