Get Adapter in Activity from Fragment - android

So I have an FragmentActivity that have an EditText and a ListFragment.
In the ListFragment I have an adapter to populete all the items.
public class XXXListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
ArrayAdapter<Spanned> adapter = new ArrayAdapter<Spanned>(inflater.getContext(),
R.layout.fragment_list_item_appearance, spannedArray);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
With the EditText I want the user to filter the listitems.
public class XXX extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quests_activity);
EditText ediText = (EditText) findViewById(R.id.editext);
ediText .addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ListFragment.this.adapter.getFilter().filter(cs);
}
...
});
}
My problem is that I can't get the context of the Listfragment with:
ListFragment.this.adapter.getFilter().filter(cs);
The following error is thrown:
No enclosing instance of the type QuestsListFragment is accessible in
scope
Any ideas how to solve this?
Ok here the whole code. I just started to use Fragments...
FragmentActivity:
public class XXX extends FragmentActivity implements ListFragmentItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx_activity);
}
#Override
protected void onStart() {
super.onStart();
EditText editText = (EditText) findViewById(R.id.edittext)
editText .addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// THIS DOESN'T WORK
XXXListFragment.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
#Override
public void onListFragmentItemClick(int position) {
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment prevFrag = fragmentManager.findFragmentByTag("xxx.details");
if (prevFrag != null)
fragmentTransaction.remove(prevFrag);
XXXDetailsFragment fragment = new XXXDetailsFragment();
Bundle b = new Bundle();
b.putInt("position", position);
fragment.setArguments(b);
fragmentTransaction.add(R.id.xxx_detail_fragment_container, fragment,
"xxx.details");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
...
}
}
...
}
ListFragment:
public class XXXListFragment extends ListFragment {
ListFragmentItemClickListener ifaceItemClickListener;
public interface ListFragmentItemClickListener {
void onListFragmentItemClick(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
ifaceItemClickListener = (ListFragmentItemClickListener) activity;
} catch (Exception e) {
Toast.makeText(activity.getBaseContext(), "Exception", Toast.LENGTH_SHORT).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Spanned[] xxx = { Html.fromHtml(getString(R.string.xxx)), ... };
ArrayAdapter<Spanned> adapter = new ArrayAdapter<Spanned>(inflater.getContext(),
R.layout.fragment_list_item_appearance, xxx);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
ifaceItemClickListener.onListFragmentItemClick(position);
}
}
The ListFragment is added in the FragmentActivity layout:
<?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="wrap_content"
android:orientation="vertical" >
...
<EditText
android:id="#+id/edittext"
style="#style/red_edittext"
android:hint="#string/exittext_input_search" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="#+id/xxx_list_fragment"
android:name="com.xxx.XXXListFragment"
android:layout_width="350dp"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+id/xxx_detail_fragment_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</FrameLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>

You must make a public method getAdapterOfList() in your listfragment class which will internally access the adapter and return it.

Related

getItem function calling twice in FragmentStatePagerAdapter?

I Have a problem with getItem() function why because it is called twice in FragmentStatePagerAdapter class.
Actually the main reason is in application having TextoSpeech functionality so getItem() function twice the text also speech twice. This is my code can u please assist me....Great thanks in advance.
Here is the code
This is MainActivity class:
public class MainActivity extends FragmentActivity{
PagerFragment pagerFragment;
Cursor mCursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rhymes_activity_main);
DBUtils utils = new DBUtils(getApplicationContext());
new DBUtils(getApplicationContext());
try {
DBUtils.createDatabase();
} catch (IOException e) {
Log.w(" Create Db "+e.toString(),"===");
}
DBUtils.openDatabase();
mCursor = utils.getResult("select * from Cflviewpagerdata order by title");
final ArrayList<PageData> myList = new ArrayList<PageData>();
while (mCursor.moveToNext()) {
myList.add(new PageData(mCursor.getInt(
mCursor.getColumnIndex("_id")),
mCursor.getString(mCursor.getColumnIndex("title")),
mCursor.getString(mCursor.getColumnIndex("view"))));
}
mCursor.close();
ListView lv = (ListView) findViewById(R.id.list_view);
ListViewAdapter lva = new ListViewAdapter(this, R.layout.list_item, myList);
lv.setAdapter(lva);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//peace of code that create launch new fragment with swipe view inside
PagerFragment pagerFragment = new PagerFragment();
Bundle bundle = new Bundle();
bundle.putInt("CURRENT_POSITION", position);
bundle.putParcelableArrayList("DATA_LIST", myList);
pagerFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, pagerFragment, "swipe_view_fragment").commit();
}
});
DBUtils.closeDataBase();
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentByTag("swipe_view_fragment");
if(f!=null){
fm.beginTransaction().remove(f).commit();
}else{
super.onBackPressed();
}
}
}
This is PagerFragment class:
public class PagerFragment extends Fragment{
private ArrayList<PageData> data;
private int currentPosition;
private String mTitle;
private FragmentActivity context;
#Override public void onAttach(Activity activity) {
context = (FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager, container, false);
ViewPager mViewPager = (ViewPager) v.findViewById(R.id.pager_view);
currentPosition = getArguments().getInt("CURRENT_POSITION");
mTitle = getArguments().getString("T_TITLE");
data = getArguments().getParcelableArrayList("DATA_LIST");
FragmentItemPagerAdapter fragmentItemPagerAdapter = new FragmentItemPagerAdapter(getFragmentManager(), data);
mViewPager.setAdapter(fragmentItemPagerAdapter);
mViewPager.setCurrentItem(currentPosition);
return v;
}
}
This is FragmentItemPagerAdapter class:
public class FragmentItemPagerAdapter extends FragmentStatePagerAdapter{
private static ArrayList<PageData> data;
public FragmentItemPagerAdapter(FragmentManager fm, ArrayList<PageData> data){
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putString(PageFragment.TITLE, data.get(position).getTitle());
args.putString(PageFragment.DESCRIPTION, data.get(position).getDes());
args.putInt("CURRENT_POSITION", position);
fragment.setArguments(args);
return fragment;
}
void deletePage(int position) {
if (canDelete()) {
data.remove(position);
notifyDataSetChanged();
}
}
boolean canDelete() {
return data.size() > 0;
}
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
return data.size();
}
public static class PageFragment extends Fragment implements OnInitListener{
public static final String TITLE = "title";
public static final String DESCRIPTION = "view";
String om;
TextToSpeech tts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
((TextView) rootView.findViewById(R.id.item_label)).setText(getArguments().getString(TITLE));
View tv = rootView.findViewById(R.id.item_des);
((TextView) tv).setText(getArguments().getString(DESCRIPTION));
Bundle bundle = getArguments();
int currentPosition = bundle.getInt("CURRENT_POSITION");
tts = new TextToSpeech( getActivity(), PageFragment.this);
om = data.get(currentPosition).getDes();
tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
return rootView;
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
This is PageData class:
This class is Object class
public class PageData implements Parcelable{
private String title;
private String view;
public PageData(){
}
public PageData(Parcel in){
title = in.readString();
view = in.readString();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(view);
}
public PageData(int picture, String title, String description){
this.title = title;
this.view = description;
}
public String getTitle() {
return title;
}
public String getDes() {
return view;
}
}
This is Xml code
fragment_item.xml:
<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="wrap_content"
android:padding="8dp"
android:orientation="vertical">
<TextView
android:id="#+id/item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10sp"
android:text="Image Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal" />
<TextView
android:id="#+id/item_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10sp"
android:text="Image Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
This is fragment_pager.xml: This is viewpager layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<android.support.v4.view.ViewPager
android:id="#+id/pager_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
This is rhymes_activity_main.xml: This is for listview of application.
<?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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:scrollbarAlwaysDrawVerticalTrack="true"
android:id="#+id/list_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
This images are my application look
This image is logcat of my application
Highlighted is my problem.
This is my code can you please help me any one.
I am new one of Android so please help
FragmentStatePagerAdapter preloads always at least 1 page.
You can try to use setUserVisibleHint to handle your logic only for visible fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Your code
}
}

android TabLayout and ViewPager does not work in Fragment

First of all, I searched a lot, but the solutions are not worked, so I am here for help. the design lib used is 23.1.1
//MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment
class = "com.tablayoutfragmenttest.FragmentTest"
android:id="#+id/hahah"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
// Fragment
public class FragmentTest extends Fragment {
private TabLayout mTablayout;
private ViewPager mVp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment, container, false);
mTablayout = (TabLayout)v.findViewById(R.id.bizfrag_tabs_id);
mTablayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mVp = (ViewPager)v.findViewById(R.id.bizfrag_vp_id);
mVp.setAdapter(new MyAdapter(getChildFragmentManager()));
mVp.setOffscreenPageLimit(0);
//mTablayout.setupWithViewPager(mVp);
//mTablayout.post(new Runnable() {
// #Override
// public void run() {
// if (ViewCompat.isLaidOut(mTablayout)) {
// mTablayout.setupWithViewPager(mVp);
// } else {
// mTablayout.addOnLayoutChangeListener(
// new View.OnLayoutChangeListener() {
// #Override
// public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// mTablayout.setupWithViewPager(mVp);
//
// mTablayout.removeOnLayoutChangeListener(this);
// }
// });
// }
// }
// });
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTablayout.post(new Runnable() {
#Override
public void run() {
mTablayout.setupWithViewPager(mVp);
}
});
}
}
//fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/bizfrag_tabs_id"
android:layout_width="match_parent"
android:layout_height="40dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/bizfrag_vp_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
//ViewPager's adapter
public class MyAdapter extends FragmentStatePagerAdapter {
public static String[] totalPossibleTabs = new String[]{"this is tab0", "this is tab1", "this is tab2", "this is tab3", "this is tab4", "this is tab5", "this is tab6", "this is tab7", "this is tab8", "this is tab9"};
public MyAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
return new Fragment();
}
#Override
public int getCount() {
return totalPossibleTabs.length;
}
#Override
public CharSequence getPageTitle(int position) {
return totalPossibleTabs[position];
}
}
when I run the app, and swipe the page, the problem is as follows:
the tab's indicator is in wrong position
Try this:-
if (ViewCompat.isLaidOut(tabLayout)) {
mTablayout.setupWithViewPager(viewPager);
} else {
tabLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(...) {
mTablayout.setupWithViewPager(viewPager);
mTablayout.removeOnLayoutChangeListener(this);
}
});
}
instead of:-
mTablayout.post(new Runnable() {
#Override
public void run() {
mTablayout.setupWithViewPager(mVp);
}
});
Thank you all guys, I finally find the point,
we just cannot use
new Fragment();
in this case for simplicity,
change it to your own Fragment.

Android saving dynamically added viewpager's fragment while coming back from another activity and reopening app

With the help of answer of the this question in StackOverflow(Remove Fragment Page from ViewPager in Android), I successfully created my project and did some modifications according to my needs.
I am able to add N number of fragments(viewpages) in my main layout and delete them until page count becomes zero.
Now, I struck with an issue.i.e. ones, if I move from my current activity which is holding this pages to other activity or if I close my app and come back,I am only able to see initial statically added fragment.
I would like to see not only initial page but also previously added pages. Should i use SharedPreferences to store dynamically added fragments?
Here is my source code:
My main layout:
<?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.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="900dp"
/>
<Button
android:id="#+id/show_items"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:textColor="#ffffff"
android:background="#49a942"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="+" />
<Button
android:id="#+id/grid_apps_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pager"
android:layout_alignParentBottom="true"
android:text="Apps"
/>
</RelativeLayout>
My MainActivity class:
public class MainActivity extends FragmentActivity implements TextProvider{
Button home;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
private ArrayList<String> mEntries = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
home = (Button) findViewById(R.id.show_items);
mEntries.add("pos 1");
mPager = (ViewPager) findViewById(R.id.pager);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder.setTitle("Add/Delete Screens");
alertDialogBuilder
.setCancelable(false)
.setNegativeButton("+",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
addNewItem();
}
})
.setPositiveButton("-",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
removeCurrentItem();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
mAdapter = new MyPagerAdapter(this.getSupportFragmentManager(), this);
mPager.setAdapter(mAdapter);
}
private void addNewItem() {
mEntries.add("Pages");
mAdapter.notifyDataSetChanged();
}
private void removeCurrentItem() {
int position = mPager.getCurrentItem();
if(position != 0){
mEntries.remove(position);
mAdapter.notifyDataSetChanged();
}
else{
Toast.makeText(getApplicationContext(), "Minimum Screens are one!", Toast.LENGTH_LONG).show();
}
}
#Override
public String getTextForPosition(int position) {
return mEntries.get(position);
}
#Override
public int getCount() {
return mEntries.size();
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private TextProvider mProvider;
private long baseId = 0;
public MyPagerAdapter(FragmentManager fm, TextProvider provider) {
super(fm);
this.mProvider = provider;
}
#Override
public Fragment getItem(int position) {
if(position == 0){
return ScreenOne.newInstance(mProvider.getTextForPosition(position));
}
if(position == 1){
return ScreenTwo.newInstance(mProvider.getTextForPosition(position));
}
return ScreenTwo.newInstance(mProvider.getTextForPosition(position));
}
#Override
public int getCount() {
return mProvider.getCount();
}
//this is called when notifyDataSetChanged() is called
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
* #param n number of items which have been changed
*/
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
}
my fragment one:
public class ScreenOne extends Fragment {
private String mText;
public static ScreenOne newInstance(String text) {
ScreenOne f = new ScreenOne(text);
return f;
}
public ScreenOne() {
}
public ScreenOne(String text) {
this.mText = text;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.screen_one, container, false);
((TextView) root.findViewById(R.id.position_one)).setText(mText);
return root;
}
}
my fragment two:
public class ScreenTwo extends Fragment {
private String mText;
public static ScreenTwo newInstance(String text) {
ScreenTwo f = new ScreenTwo(text);
return f;
}
public ScreenTwo() {
}
public ScreenTwo(String text) {
this.mText = text;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.screen_two, container, false);
((TextView) root.findViewById(R.id.position_two)).setText(mText);
return root;
}
}
Thanks & Regards,
Aditya. J
Just override this method in FragmentpagerAdapter:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(ViewGroup container, int position, Object object);
}
And remove:
super.destroyItem(ViewGroup container, int position, Object object);

Fragment: Get object from activity (Tab View)

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.

android fragments , activity

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

Categories

Resources