i'm very new to Android programming, and i'm trying to make the instantiateItem on my SlidingTabsBasicFragment class, to return the fragment of my ConversationsFragment.
In my understanding, my Class ConversationsFragment returns a fragment, that would be instantiated. But instead, nothing shows at the second page.
I'm using the SlidingTabsBasic sample to make this:
Main Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("Logs", "first");
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
//ConversationsFragment fragment = new ConversationsFragment();
//transaction.replace(R.id.sample_content_fragment, new ConversationsFragment());
transaction.commit();
}
}
SlidingTabsBasicFragment:
package com.example.android.slidingtabsbasic;
import com.example.android.common.logger.Log;
import com.example.android.common.view.SlidingTabLayout;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;
/**
* A basic sample which shows how to use {#link com.example.android.common.view.SlidingTabLayout}
* to display a custom {#link ViewPager} title strip which gives continuous feedback to the user
* when scrolling.
*/
public class SlidingTabsBasicFragment extends Fragment {
static final String LOG_TAG = "SlidingTabsBasicFragment";
/**
* A custom {#link ViewPager} title strip which looks much like Tabs present in Android v4.0 and
* above, but is designed to give continuous feedback to the user when scrolling.
*/
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
/**
* Inflates the {#link View} which will be displayed by this {#link Fragment}, from the app's
* resources.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sample, container, false);
}
// BEGIN_INCLUDE (fragment_onviewcreated)
/**
* This is called after the {#link #onCreateView(LayoutInflater, ViewGroup, Bundle)} has finished.
* Here we can pick out the {#link View}s we need to configure from the content view.
*
* We set the {#link ViewPager}'s adapter to be an instance of {#link SamplePagerAdapter}. The
* {#link SlidingTabLayout} is then given the {#link ViewPager} so that it can populate itself.
*
* #param view View created in {#link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
*/
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new CustomPagerAdapter(getFragmentManager(),getActivity()));
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
// END_INCLUDE (setup_slidingtablayout)
}
// END_INCLUDE (fragment_onviewcreated)
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public CharSequence getPageTitle(int position) {
return "Item " + (position + 1);
}
#Override
public Fragment getItem(int position) {
if(position==0){
// return fragment
}else{
ConversationsFragment fragment = new ConversationsFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
}
And this is my ConversationsFragment:
public class ConversationsFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private List conversationsListItemList; // at the top of your fragment listW
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static ConversationsFragment newInstance(String param1, String param2) {
ConversationsFragment fragment = new ConversationsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ConversationsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
conversationsListItemList = new ArrayList();
conversationsListItemList.add(new ConversationsListItem("Example 1","conversa"));
conversationsListItemList.add(new ConversationsListItem("Example 2","conversa"));
conversationsListItemList.add(new ConversationsListItem("Example 3","conversa"));
mAdapter = new ConversationsListAdapter(getActivity(), conversationsListItemList);
/* mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conversations, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(String id);
}
}
Screenshots:
First Screen:
https://goo.gl/photos/Ze5ThZgevGaALDj47
Second Screen:
https://goo.gl/photos/x7JPnESAtZsBT5DC8
And now this errors appears:
06-16 12:32:58.946 12228-12228/com.example.android.slidingtabsbasic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.slidingtabsbasic, PID: 12228
java.lang.NullPointerException
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:417)
at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:412)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
I think problem with your code is returning View and Fragment
below code worked for me
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public CharSequence getPageTitle(int position) {
return "" + tabsTitle[position];
}
#Override
public Fragment getItem(int position) {
if(position==0){
// return fragment
}else{
ConversationsFragment fragment = new ConversationsFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Related
I have an issue where my view pager is showing blank fragment when I back press.
I have a grid fragment(consider Fragment A) where when I click on a button its navigates me to another grid fragment(Consider Fragment B),when I click on a button it navigates me to a ViewPager(Fragment C) which has three Slidingtabs. each Tab layout has a listview in which if I select an item it navigates me to another fragment(Fragment D).My problem is when I backpress from Fragment D the ViewPager sliding tabs(Fragment C) are showing blank empty screen.Can anyone tell me how to resolve this issue.
public class RetrievalListOperation extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
List<VehicleInfo> vehicleInfos=new VehicleInfoData().getVehicleData();
DataService dataService;
List<VinInfoDTO> retlist;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RetrievalListOperation.
*/
// TODO: Rename and change types and number of parameters
public static RetrievalListOperation newInstance(String param1, String param2) {
RetrievalListOperation fragment = new RetrievalListOperation();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public RetrievalListOperation() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrieval_list_operation, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
dataService=new DataService(getActivity());
retlist=dataService.getRetrievalJobsForStatus("Open");
super.onViewCreated(view, savedInstanceState);
RecyclerView rv = (RecyclerView) getActivity().findViewById(R.id.retrieval_operation_rview);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity().getApplicationContext());
rv.setLayoutManager(llm);
RetrievalOpenAdapter adapter=new RetrievalOpenAdapter(retlist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecycleItemClickListener(getActivity().getApplicationContext(), new RecycleItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
final TextView vin=(TextView)view.findViewById(R.id.ret_txt_VIN);
final TextView model=(TextView)view.findViewById(R.id.ret_txt_model);
final TextView variant=(TextView)view.findViewById(R.id.ret_txt_variant_no);
final TextView desc=(TextView)view.findViewById(R.id.ret_txt_description);
// final TextView color=(TextView)view.findViewById(R.id.ret_txt_color);
String VIN=vin.getText().toString();
Log.e("--Recycler onTouch VIN-", VIN);
JobsDTO det = dataService.getVehicleDetails(VIN);
String detail=det.JobID+" / SyncStatus: "+det.SyncStatus+" /Location Lat"+det.locationDTO.Latitude+" lng"+det.locationDTO.Longitude;
Log.e("---RetoPenList---", detail);
Bundle b=new Bundle();
b.putString("VIN", VIN);
b.putString("model", model.getText().toString());
b.putString("variant", variant.getText().toString());
b.putString("desc",desc.getText().toString());
// b.putString("color",color.getText().toString());
b.putString("job id",det.JobID);
Log.e("---Bundle Values--", " MODEL: " + model.getText().toString() + " VARIANT :" + variant.getText().toString() + " DESC:" + desc.getText().toString() + " COLOR :" );
Fragment fragment=new RetrievalMapOperation().newInstance("a" ," b");
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).addToBackStack("RetrievalList")
.commit();
fragment.setArguments(b);
}
})
);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public class RetrievalOpenAdapter extends RecyclerView.Adapter<RetrievalOpenAdapter.ViewHolder>
{
List<VinInfoDTO> vinfo;
RetrievalOpenAdapter(List<VinInfoDTO> vinfo)
{
this.vinfo=vinfo;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.operationscardlayout, parent, false);
ViewHolder pvh = new ViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.vehicleNumber.setText(vinfo.get(position).VIN);
holder.variantNumber.setText(vinfo.get(position).Variant);
// holder.color.setText(vinfo.get(position).Color);
holder.desc.setText(vinfo.get(position).Desc);
holder.model.setText(vinfo.get(position).Model);
// Log.e("--RetCOLOR--",""+holder.color.getText().toString());
// holder.time.setText(vinfo.get(position).getTime());
}
#Override
public int getItemCount() {
return vinfo.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView vehicleNumber;
TextView variantNumber;
TextView model,color,desc ;
public ViewHolder(View itemView) {
super(itemView);
cv=(CardView)itemView.findViewById(R.id.operation_retrieval_cview);
vehicleNumber=(TextView)itemView.findViewById(R.id.ret_txt_VIN);
variantNumber=(TextView)itemView.findViewById(R.id.ret_txt_variant_no);
model=(TextView)itemView.findViewById(R.id.ret_txt_model);
// color= (TextView)itemView.findViewById(R.id.ret_txt_color);
desc=(TextView)itemView.findViewById(R.id.ret_txt_description);
//time=(TextView)itemView.findViewById(R.id.txt_srtime);
}
}
}
}
RetrievalTabs.java(slidinglayout)
public class RetrievalTabs extends Fragment {
NavigationDrawerActivity nav;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
CharSequence Titles[] = {"Open", "WIP", "Complete"};
int Numboftabs = 3;
ViewPager pager;
FrameLayout frameLayout;
LinearLayout linear;
private TextView actionBarTitle;
SlidingTabLayout tabs;
RetrievalPagerAdapter adapter;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RetrievalTabs.
*/
// TODO: Rename and change types and number of parameters
public static RetrievalTabs newInstance(String param1, String param2) {
RetrievalTabs fragment = new RetrievalTabs();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public RetrievalTabs() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
View actionBarCustomView = getActivity().getActionBar().getCustomView();
actionBarTitle = (TextView) actionBarCustomView.findViewById(R.id.head_text);
actionBarTitle.setText("Retrieval");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrieval_tabs, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tabs = (SlidingTabLayout) getActivity().findViewById(R.id.retrieval_tabs);
adapter = new RetrievalPagerAdapter(getFragmentManager(), Titles, Numboftabs);
pager = (ViewPager) getActivity().findViewById(R.id.retrieval_pager);
pager.setAdapter(adapter);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
RetrievalPagerAdapter.java
public class RetrievalPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
android.app.Fragment tab1, tab2, tab3;
FragmentManager fm;
MyApplication app;
public RetrievalPagerAdapter(FragmentManager fm, CharSequence mTitles[], int NumOfTabs) {
super(fm);
this.fm = fm;
this.Titles = mTitles;
this.NumbOfTabs = NumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
#Override
public android.app.Fragment getItem(int position) {
if (position == 0) {
tab1 = new RetrievalListOperation().newInstance("a", "b");
return tab1;
} else if (position == 1) {
tab2 = new RetrievalInProgressList().newInstance("a", " b");
return tab2;
} else {
tab3 = new RetrievalCompletedList().newInstance("a", "b");
return tab3;
}
}
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
}
I'm relatively new to the Android development and encountered the following problem:
I have a ListView with a corresponding ArrayAdapter which delivers simple item views. The item views are structured in a simple RelatveLayout manner revealing some behavior if clicked or long-pressed using the callback methods of OnItemClickListener and OnItemLongClickListener. This works fine so far. However, if I add an ImageButton to the item view with a corresponding onClick-callback, the original listener-methods on the item view itself don't work any more. The items in the ListView can't be selected any more as well. Why?
public class ProfileActivity extends Activity implements ActionBar.TabListener {
private static final String DEBUG_TAG = ProfileActivity.class
.getSimpleName();
private XMLBinder profilesDao;
private Config config;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getActionBar().setSubtitle("Game Profiles");
// load profiles:
profilesDao = new XMLBinder(this);
try {
config = profilesDao.deserialize(Config.class,
R.raw.default_profiles);
} catch (Exception e) {
if (BuildConfig.DEBUG) {
Log.e(DEBUG_TAG, e.toString());
}
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager(),
config.getCategories());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
// SharedPreferences pref = getSharedPreferences("AGT",
// Context.MODE_PRIVATE);
// SharedPreferences.Editor prefEditor = pref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.profile, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Category> categories;
/** */
public SectionsPagerAdapter(final FragmentManager fm,
final List<Category> categories) {
super(fm);
this.categories = categories;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
final List<Profile> profiles = config.getCategories().get(position)
.getProfiles();
return PlaceholderFragment.newInstance(position + 1, profiles,
ProfileActivity.this);
}
#Override
public int getCount() {
// Show x total pages.
return this.categories.size();
}
#Override
public CharSequence getPageTitle(int position) {
return categories.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements
OnItemClickListener {
private List<Profile> list;
private ProfilesAdapter profilesAdapter;
private Context context;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*
* #param list
*/
public static PlaceholderFragment newInstance(int sectionNumber,
List<Profile> list, Context context) {
final PlaceholderFragment fragment = new PlaceholderFragment(list,
context);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
super();
}
/** */
public PlaceholderFragment(List<Profile> list, Context context) {
this();
this.list = list;
this.context = context;
this.profilesAdapter = new ProfilesAdapter(this.context,
R.layout.view_profile, this.list);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_profile,
container, false);
// Configure the ListView with Adapter
final ListView profilesView = (ListView) rootView
.findViewById(R.id.profilesView);
profilesView.setAdapter(profilesAdapter);
// #TODO:
// profilesView.setDivider();
// profilesView.setEmptyView(emptyView);
profilesView.setOnItemClickListener(this);
profilesAdapter.notifyDataSetChanged();
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (view != null) {
final GameProfile selectedProfile = (GameProfile) parent
.getItemAtPosition(position);
final Intent intent = new Intent(this.context,
ChessClockActivity.class);
intent.putExtra(GameProfile.INTENT_EXTRA_SELECTED_PROFILE,
selectedProfile);
startActivity(intent);
}
}
}
/**
* #author Andy
*
*/
public static class ProfilesAdapter extends ArrayAdapter<Profile> {
private Context context;
private List<Profile> profiles;
/** */
public ProfilesAdapter(Context context, int resource,
List<Profile> profiles) {
super(context, resource, profiles);
this.context = context;
this.profiles = profiles;
}
#Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
View profileView = convertView;
if (null == profileView) {
final LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
profileView = inflater.inflate(R.layout.view_profile, null);
}
final TextView name = (TextView) profileView
.findViewById(R.id.profile_name);
name.setText(profiles.get(position).getTitle());
final TextView hint = (TextView) profileView
.findViewById(R.id.profile_desc);
hint.setText(profiles.get(position).getHint());
hint.setMaxLines(1);
hint.setEllipsize(TruncateAt.END);
return profileView;
}
}
}
use
android:descendantFocusability="blocksDescendants"
android:focusable="false"
hope it helps
Dont know if it's gonna help
ImageView yourImg=(ImageView).findViewById(R.id.icon);
yourImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// things you want to do
}
});
I am trying to make the Contact tab in my app to list the users address book's name and phone number, however when I set the adapter for contactlist the app no longer shows its tabs and the fragment is empty.
Code:
package com.spgrn.smsim;
import java.util.ArrayList;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
String phoneNumber;
ListView contactlist;
ArrayList <String> aa= new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactlist= (ListView) findViewById(R.id.contactv);
getNumber(this.getContentResolver());
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
Log.v("I", "curtab="+ mSectionsPagerAdapter.getCount() + "i=" + i);
if (i != 1)
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),
false);
if (i == 1)
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),
true);
}
}
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(name + phoneNumber);
aa.add(name + "\n" + phoneNumber);
}
Log.v("Contacts", "Total= " + phones.getCount());
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,aa);
contactlist.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_compose) {
Intent intent = new Intent(this, NewMessage.class);
this.startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position){
case 0:
Fragment fragmentContacts = new FragmentContacts();
return fragmentContacts;
case 1:
Fragment fragmentMessages = new FragmentMessages();
return fragmentMessages;
case 2:
Fragment fragmentAccounts = new FragmentAccounts();
return fragmentAccounts;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
//Make fragments for each tab
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
return rootView;
}
}
public static class FragmentMessages extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentMessages() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,
container, false);
return rootView;
}
}
public static class FragmentAccounts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentAccounts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_accounts,
container, false);
return rootView;
}
}
//End of Tab Fragments
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Also, in the debugger I noticed the main activity was suspended due to a run time exception. Here is the stack:
Thread [<1> main] (Suspended (exception RuntimeException))
<VM does not provide monitor information>
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2195
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2245
ActivityThread.access$800(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 135
ActivityThread$H.handleMessage(Message) line: 1196
ActivityThread$H(Handler).dispatchMessage(Message) line: 102
Looper.loop() line: 136
ActivityThread.main(String[]) line: 5017
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 515
ZygoteInit$MethodAndArgsCaller.run() line: 779
ZygoteInit.main(String[]) line: 595
XposedBridge.main(String[]) line: 126
NativeStart.main(String[]) line: not available [native method]
Thanks!
Edit: Looking more, I think the list needs to be generated in the fragments class, but I am not sure what to do with the context. I keep getting a NullPointerException.
Code:
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
Context context;
String phoneNumber;
ListView contactlist;
ArrayList <String> aa= new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
contactlist = (ListView) rootView.findViewById(R.id.contactv);
getNumber(context.getContentResolver());
return rootView;
}
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(name + phoneNumber);
aa.add(name + "\n" + phoneNumber);
}
Log.v("Contacts", "Total= " + phones.getCount());
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
.getApplicationContext(),
android.R.layout.simple_list_item_1,aa);
contactlist.setAdapter(adapter);
}
}
write
context=container.getContext();
in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
contactlist = (ListView) rootView.findViewById(R.id.contactv);
context=container.getContext();
getNumber(context.getContentResolver());
return rootView;
}
I can't seem to find a way to give different text to a dynamically created fragment for my pageviewer-supoorted application. I've came to a point of my codding where I got stuck. For my application I want to have 400-500 dynamically created fragments, where you can horizontally slide thru them and every content of the fragment to be the same (repeating the same fragment) and the only different thing to be the text on them.
Here's where I got stuck at my codding :
package com.example.testarearg;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/ private String mText; // display this text in your fragment
public static Fragment getInstance(String text) {
Fragment f = new Fragment();
Bundle args = new Bundle();
args.putString("text", text);
f.setArguments(args);
return f;
}
public void onCreate(Bundle state) {
super.onCreate(state);
setmText(getArguments().getString("text"));
// rest of your code
}
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
}
}
You need to create your own custom Fragment:
import android.support.v4.app.Fragment;
public class YourFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
TextView tv = (TextView) v.findViewById(R.id.yourtextview);
tv.setText(getArguments().getString("text"));
return v;
}
public static YourFragment newInstance(String text) {
YourFragment f = new YourFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
}
And then modify your adapter. The basic idea is that the adapter
contains the Strings that you want to display and the getItem(...)
method will choose the text.
public class MyPagerAdapter extends FragmentPagerAdapter {
private String [] strings;
public MyPagerAdapter(FragmentManager fm, String [] stringstodisplay) {
super(fm);
this.strings = stringstodisplay;
}
#Override
public Fragment getItem(int pos) {
return YourFragment.newInstance(strings[pos]);
}
#Override
public int getCount() {
return 500; // or strings.length to be save
}
}
From your Activity, you hand over the String array containing the different strings to the adapter.
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the content that your fragments will display
String [] strings = new String[500];
for(int i = 0; i < 500; i++) {
strings[i] = "This is Fragment " + i;
}
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), strings));
}
}
I currently have the following code which I found as an example and modified slightly:
package com.boy.test;
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new Facebook();
Bundle args = new Bundle();
args.putInt(Facebook.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Welcome".toUpperCase(l);
case 1:
return "Facebook".toUpperCase(l);
case 2:
return "Twitter".toUpperCase(l);
case 3:
return "dashboard".toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class Facebook extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
private WebView faceBook;
public Facebook() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_facebook, container, false);
return rootView;
}
}
}
What I want to do is add facebook into the second tab. This is code I have in another class for doing so:
public class Facebook extends Activity {
private WebView faceBook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
faceBook = new WebView(this);
faceBook.getSettings().setJavaScriptEnabled(true);
final Activity act = this;
faceBook.setWebViewClient(new WebViewClient(){
public void onRecievedError(WebView view,int errorCode,String description,String failingUrl){
Toast.makeText(act,description,Toast.LENGTH_SHORT).show();
}
});
faceBook.loadUrl("http://m.facebook.com/pages/hi");
setContentView(faceBook);
}
I tried simply copying it into my static facebook fragment and got errors. I also tried making that extend fragment activity instead of fragment and got more errors. Can anyone advise me on to how to best approach this?
Thank you.
first of all you don't need a Facebook activity, you will have to override Fragment's onCreateView() method in class Facebook to return a WebView.
try this,
your fragment should look like following,
public final class MyTab extends Fragment {
public static MyTab newInstance(int type) {
MyTab tab = new MyTab();
tab.mType = type;
return fragment;
}
private int mType = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*
* Create a web view here, and on the basis of mType decide what to load.
* and return that web view.
*/
}
}
and your adapter will be
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return MyTab.newInstance(position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Welcome".toUpperCase(l);
case 1:
return "Facebook".toUpperCase(l);
case 2:
return "Twitter".toUpperCase(l);
case 3:
return "dashboard".toUpperCase(l);
}
return null;
}
}