I have set up a swipe tab using fragments in the action bar. For each view of the tab, i have a gridview with images i want to create but i can't use both an activity and fragments. So how do i create the GridView? How are fragments supposed to work with activities in such cases? This is how i've done it so far.
public class SignsActivity extends FragmentActivity {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signs);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Warning").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Information").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Prohibition").setTabListener(tabListener));
}
}
activity_signs.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" />
ProhibitionSigns.java
public class ProhibitionSigns extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridview = (GridView) findViewById(R.id.grid_view);
gridview.setAdapter(new ImageAdapterPro(this));
gridview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
//sending the image id to full screen
Intent intent = new Intent(getApplicationContext(), FullImage.class);
intent.putExtra("id", position);
startActivity(intent);
}
});
}
grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android= "http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns ="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode = "columnWidth"
android:id="#+id/grid_view"
>
ImageAdapter.java
public class ImageAdapter extends BaseAdapter{
private Context context;
public Integer[] myImages = {
R.drawable.ic_images_1, R.drawable.ic_images_2, R.drawable.warn,
R.drawable.ic_images_6 };
public ImageAdapter (Context c){
context = c;
}
#Override
public int getCount() {
return myImages.length;
}
#Override
public Object getItem(int arg0) {
return myImages[arg0];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview = new ImageView(context);
imageview.setImageResource(myImages[position]);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageview.setLayoutParams(new GridView.LayoutParams(70,70));
return imageview;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragement for new Tab
//
return new ProhibitionSigns();
case 1:
//.......
}
return null;
your ProhibitionSigns should extend Fragment not Activity
so the modified code according to fragment is
public class ProhibitionSigns extends Fragment {
GridView gridview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.grid_layout, container, false);
gridview = (GridView) findViewById(R.id.grid_view);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gridview.setAdapter(new ImageAdapterPro(getActivity()));
gridview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
//sending the image id to full screen
Intent intent = new Intent(getActivity(), FullImage.class);
intent.putExtra("id", position);
getActivity().startActivity(intent);
}
});
}
}
I hope this would help you
Related
I'm developing a social Android app, in which I have three fragments. In my second fragment (friends), I want to have an options menu (search, contacts, etc.)
Something like this:
You have to implement Pageviewer here is example ViewPager
add in viewpager library in xml file
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
herre is instance of viewpager in oncreate method of your Mainactivity
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MultiPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setCurrentItem(1);
GetAllApplications();
custmAdapter = new CustomAdapter(this, systemAppsInfo);
init();
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
viewPager.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
Adapter for the pager is here
public class MultiPagerAdapter extends FragmentPagerAdapter {
public MultiPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 1:
// Top Rated fragment activity
return new ApplicationsFragment();
case 2:
// Games fragment activity
return new SearchAppFragment();
case 0:
// Games fragment activity
return new RecentAppsFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
here is fragment where your search is implemented
public class SearchAppFragment extends Fragment {
Utitlity utitlity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sec_fragment, container, false);
final EditText editSearch = (EditText) rootView.findViewById(R.id.edit_search_fragment);
ListView lv = (ListView) rootView.findViewById(R.id.app_list);
final CustomAdapter customAdapter = new CustomAdapter(getContext(), MainActivity.systemAppsInfo);
utitlity = new Utitlity(getContext());
lv.setAdapter(customAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
Intent LaunchIntent = getContext().getPackageManager().getLaunchIntentForPackage(MainActivity.systemAppsInfo.get(position).getPname());
startActivity(LaunchIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
how can I can access in this example the object "selectedBox" from the fragment? I need it in the main activity for testing connection and in the fragment.
In the moment I create it in the main and the fragment.
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener{
private ViewPager viewPager;
private ActionBar actionBar;
private MainTabAdapter mAdapter;
private String[] tabs = { "Live" };
private box selectedBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new MainTabAdapter(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) {
}
});
selectedBox = new box(this);
}
public void onResume(){
super.onResume();
if(selectedBox.getId() != -1){
checkReachable(selectedBox.getIpPort());
}else {
Intent intent = new Intent(this, SettingsActivity.class);
this.startActivity(intent);
finish();
}
}
private void checkReachable(String ipPort) {
Log.d("XML Request", "CHECK BOX");
String e2About = "http://" + ipPort + "/web/about";
getXml.DownloadCompleteListener dcl = new getXml.DownloadCompleteListener() {
#Override
public void onDownloadComplete(String result) {
if (!result.contains("<e2enigmaversion>")) {
Toast.makeText(getApplicationContext(), "Active box not reachable.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
}else{
viewPager.setAdapter(mAdapter);
}
}
};
getXml downloader = new getXml(dcl);
downloader.execute(e2About);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainTabAdapter
public class MainTabAdapter extends FragmentPagerAdapter {
public MainTabAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new MainFragmentLive();
}
return null;
}
#Override
public int getCount() {
return 1;
}
}
MainFragmentLive.java
public class MainFragmentLive extends ListFragment {
private box selectedBox;
private List<String> bouquetListString;
private ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_live, container, false);
Log.d("Position", "Main Live Set Box");
selectedBox = new box(getActivity());
bouquetListString = selectedBox.getBouquets().get(2);
if(bouquetListString.size() < 1){
getBouquetBox();
}
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, bouquetListString);
setListAdapter(adapter);
ImageButton reloadBouquet = (ImageButton) view.findViewById(R.id.reloadBouquet);
reloadBouquet.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
getBouquetBox();
}
});
setHasOptionsMenu(true);
return view;
}
public void onListItemClick(ListView l, View v, int position, long id) {
SharedPreferences savedData = getActivity().getSharedPreferences("box",0);
SharedPreferences.Editor editor = savedData.edit();
editor.putInt("boId", position);
editor.apply();
Intent gotoChannels = new Intent(getActivity(), ChannelListActivity.class);
startActivity(gotoChannels);
}
public void getBouquetBox(){
getXml.DownloadCompleteListener dcl = new getXml.DownloadCompleteListener() {
#Override
public void onDownloadComplete(String result) {
selectedBox.delBouquets();
bouquetListString.clear();
String [] tags = {"e2servicereference", "e2servicename"};
List<List<String>> bouquetsList = parseXml.parseXmlByTag(result, tags);
selectedBox.addBouquets(bouquetsList);
bouquetListString.addAll(selectedBox.getBouquets().get(2));
adapter.notifyDataSetChanged();
}
};
Log.d("XML Request", "GET BOUQUET");
getXml downloader = new getXml(dcl);
downloader.execute("http://" + selectedBox.getIpPort() + "/web/getservices");
}
}
activity_main.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">
</android.support.v4.view.ViewPager>
fragment_main_live.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="8dp">
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:text="#string/selectBouquet"
style="#style/header1"/>
<ImageButton
android:layout_width="0dip"
android:layout_height="wrap_content"
android:id="#+id/reloadBouquet"
android:src="#drawable/ic_action_refresh"
android:contentDescription="#string/search"
android:layout_weight=".20"
android:layout_gravity="bottom"/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/list" />
</LinearLayout>
You need to create an interface to your activity from your fragment. Something like:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener,MainFragment.getSelectedBox {
private ViewPager viewPager;
private ActionBar actionBar;
private MainTabAdapter mAdapter;
private String[] tabs = { "Live" };
private box selectedBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
}
//called from the MainFragment
#Override
public void AccessSelectedBox {
this.box = <do something with box>
}
}
Fragment Class
public class MainFragment extends ListFragment {
//interface to the MainActivity activity class
private getSelectedBox listener;
public interface getSelectedBox {
public void AccessSelectedBox();
}
}
Here is a good article on this: http://www.vogella.com/articles/AndroidFragments/article.html.
I am currently using TouchImageView to allow zooming in and out but now, I need also a View Pager using image view. How do I merge those two together? must I inflate the layout?
this is my viewpager
public class Main extends FragmentActivity implements AdapterView.OnItemSelectedListener, ViewPager.OnPageChangeListener{
private ViewPager viewPager;
String[] mImageIds;
private Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayImage();
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(this);
//gallery = (Gallery) findViewById(R.id.gallery);
//gallery.setAdapter(new ImageAdapter());
//gallery.setOnItemSelectedListener(this);
//textView = (TextView) findViewById(R.id.title);
handler = new Handler();
}
public void displayImage()
{
ArrayList<String> mStringList= new ArrayList<String>();
File strPath = new File(Environment.getExternalStorageDirectory() + "/Covers");
int lists = strPath.listFiles().length;
Log.d("number of items in array ",String.valueOf(lists));
File yourDir = new File(strPath, "");
for (File f : yourDir.listFiles()) {
if (f.isFile())
{
String name = f.getName();
String v = strPath + "/" + name;
mStringList.add(v);
}
}
mImageIds = new String[mStringList.size()];
mImageIds = mStringList.toArray(mImageIds);
for(int i = 0; i < mImageIds.length ; i++){
//Log.d("string is",(mImageIds[i]));
}
}
// gallery item selected
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
updateUI(i);
}
// view pager item selected
public void onPageSelected(int i) {
updateUI(i);
}
private void updateUI(final int i) {
handler.post(new Runnable() {
public void run() {
//gallery.setSelection(i);
viewPager.setCurrentItem(i);
///textView.setText("Photo #" + i);
}
});
}
public void onNothingSelected(AdapterView<?> adapterView) { }
public void onPageScrolled(int i, float v, int i1) { }
public void onPageScrollStateChanged(int i) { }
public class ImageAdapter extends BaseAdapter implements OnTouchListener {
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(Main.this);
imageView.setOnTouchListener(this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
public class EnableDisableViewPager extends ViewPager {
private boolean enabled = true;
public EnableDisableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if(enabled)
return super.onInterceptTouchEvent(arg0);
return false;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mImageIds.length;
}
#Override
public Fragment getItem(final int position) {
return new Fragment() {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = new ImageView(Main.this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
return imageView;
}
};
}
}
}
and its xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout android:layout_height="0px"
android:layout_width="fill_parent"
android:layout_weight="1"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip" />
</FrameLayout>
</LinearLayout>
Create an FragmentActivity whose layout consists of View Pager.
Add a Fragment foreach image whose layout consists of
TouchImageView.
Add these list of fragments to the View pager. Thats it. Pinch Zoom and pager both works.
Like this:
#Override
protected void onStart() {
super.onStart();
List<Fragment> fragments = new Vector<Fragment>();
String url1 = "someurl1.jpg";
Bundle Image1 = new Bundle();
Image1.putString("image_url", url1);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image1));
String url2 = "someurl2.jpg";
Bundle Image2 = new Bundle();
Image2.putString("image_url", url2);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image2));
//and so on.
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.animate();
mPager.setAdapter(this.mPagerAdapter);
}
MainActivity.java
public class MainActivity extends SherlockFragmentActivity {
static MyListfragment mf;
ViewPager mpager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mf = new MyListfragment();
ft.add(android.R.id.content,mf).commit();
}}
MyListfragment.java
public class MyListfragment extends SherlockListFragment {
MyDisplayfragment tempFrag;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Connector.selection = position;
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
if(position==0)
{
tempFrag=new MyDisplayfragment();
tempFrag.setLayout(R.layout.law);
subFragmentAdapter mAdapter = new subFragmentAdapter(getChildFragmentManager());
tempFrag.setViewPagerAdapter(mAdapter);
}
ft.replace(android.R.id.content,tempFrag);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity(),
layout, Connector.list));
}}
MyDisplayfragment.java
public class MyDisplayfragment extends SherlockFragment {
int resource;
FragmentPagerAdapter mAdapter;
ViewPager v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if(Connector.selection==-1)
resource=R.layout.displayfragment;
return inflater.inflate(resource, container, false);
}
public void setViewPagerAdapter(FragmentPagerAdapter x)
{
mAdapter=x;
}
public void setLayout(int layout)
{
resource=layout;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
ViewPager pager=(ViewPager) view.findViewById(R.id.mpager);
pager.setAdapter(mAdapter);
}}
subFragment.java
public final class subFragment extends SherlockFragment {
private int layout;
public static subFragment newInstance(int content) {
subFragment fragment = new subFragment();
fragment.layout=content;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(layout,container,false);
}}
subFragmentAdapter.java
public class subFragmentAdapter extends FragmentPagerAdapter{
int[] LAYOUT={R.layout.cccc,R.layout.aaaa,R.layout.bbb};
private int mCount;
public subFragmentAdapter(FragmentManager fm) {
super(fm);
mCount = LAYOUT.length;
}
#Override
public Fragment getItem(int position) {
return subFragment.newInstance(LAYOUT[position]);
}
#Override
public int getCount() {
return mCount;
}
}
Connector.java
public class Connector {
static int selection = -1;
static String list[] = { "Law" };}
In the above project
1)MyListfragment.java is used for navigation
2)MyDisplayfragment.java is used to display according to selection made in MyListFragment
3)Connector.java is used to communicate between the above two fragments
4)subFragment.java is used to populate Viewpager with Fragments
5)subFragmentAdapter.java is th adapter for Viewpager
When i run this project the viewpager seems to be blank and doesnot show any of the child fragments and after debugging i saw that onCreateView() method of subFragment.java is not called.
My question is why the onCreateView() method is not being called
Please refer to Luksprog's comment for the answer.
I have two listfragment and one fragment in my application. I show you first fragment.
The application starts, Asynctask retrieves data and put them in arrayNews.
I think the problem is the update of listview or adapter in listfragment that does not refresh.
If I change the phone's orientation => listfragment (+ listview) appears correctly.
If I go to fragment 3 (fragment in 2 and 3 in memory), then come back on fragment 1 => it works correctly.
Sorry for my english ^^
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static ArrayList<Data> arrayNews = new ArrayList<Data>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> listeFragments = new Vector<Fragment>();
listeFragments.add(Fragment.instantiate(this, ActualiteFragment.class.getName()));
listeFragments.add(Fragment.instantiate(this, DossierFragment.class.getName()));
listeFragments.add(Fragment.instantiate(this, ForumFragment.class.getName()));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), listeFragments);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
if (arrayDossier.size() == 0 && arrayDossier.size() == 0)
{
chargement_donnees();
}
}
public void chargement_donnees()
{
AsyncTaskChargement chargNews = new AsyncTaskChargement();
chargNews.execute();
}
public class AsyncTaskChargement extends AsyncTask<Void, Integer, Void>
{
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Chargement des données ...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
arrayNews = ContainerData_news.getFeeds();
return null;
}
#Override
protected void onPostExecute(Void result)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_refresh:
chargement_donnees();
return true;
default:
return false;
}
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
List<Fragment> listeFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> listeFragments)
{
super(fm);
this.listeFragments = listeFragments;
}
#Override
public Fragment getItem(int position)
{
return listeFragments.get(position);
}
#Override
public int getCount()
{
return listeFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
switch (position)
{
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
public static class ActualiteFragment extends ListFragment
{
public ActualiteFragment()
{
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setListAdapter(new AdapterListe(getActivity(), arrayNews));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.listfragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
...
}
}
}
I found an easy way to update such list
Steps would be.:
1. declare onCreateView in ListFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.TheLayoutContainingAListView, container, false);
return view;
}
TheLayoutContainingAListView.xml should contain only a listview
<?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="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
The android:id must be "#android:id/list" . however you may try other things.. I didn't..
2. In onPostExecute of your AsyncTask (Asynctask should be in MainActivity), do everything that you want to do.. i.e. declare an adapter, and setAdapter
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
lv = (ListView) findViewById(android.R.id.list);
CustomAdapter adapt = new CustomAdapter(MainActivity.this,
android.R.id.list, fetch); //You can use ArrayAdapter.. i wanted a custom one
lv.setAdapter(adapt);
showFragment(YOUR Fragment, false);
super.onPostExecute(result);
}
showFragment is just a function i used to show a particular fragment and hide all others.. you can easily achieve it by FragmentTransaction show() and hide() methods.
Use youradapter.notifyDataSetChanged(); in onPostExecute to force a redraw of your list.