I'm busy creating an application that uses fragments and tabs. However I was the tabs to do different things depending on which fragment is called.
Here is my main method, What I'm trying to accomplish here is instantiating the activity_main.xml which is listed below and in that xml I'll load a fragment in, this way I can alter the way the tabs work depending on which fragment is called.
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottom_bar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Fragment manager deals with switching fragments within the viewpager
final FragmentManager FM = getSupportFragmentManager();
final FavoriteFragment FF = new FavoriteFragment();
final PlaceholderFragment HF = new PlaceholderFragment();
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.tab_home)
{
Intent intent = new Intent(getApplicationContext(),HomeFragment.class);
startActivity(intent);
}
else
if (tabId == R.id.tab_favorites)
{
FM.beginTransaction().replace(R.id.fragContainer,FF).commit();
}
else if (tabId == R.id.tab_booked)
{
}
if (tabId == R.id.tab_inbox)
{
Intent intent = new Intent(getApplicationContext(),InboxActivity.class);
startActivity(intent);
}
else if (tabId == R.id.tab_profile)
{
Intent intent = new Intent(getApplicationContext(),ProfileActivity.class);
startActivity(intent);
}
}
});
}
/**
* 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;
}
}
/**
* 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);
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SEE";
case 1:
return "DO";
case 2:
return "STAY";
case 3:
return "ENJOY";
}
return null;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.iconiccode.where.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="105dp"
android:id="#+id/fragContainer">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
<!--Bottom Bar-->
<com.roughike.bottombar.BottomBar
android:id="#+id/bottom_bar"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
app:bb_tabXmlResource="#xml/bottombar_tabs" />
</android.support.design.widget.CoordinatorLayout>
Homefragment, This is the first fragment behind called.
public class HomeFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private ViewPager mViewPager;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
int tabNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String tabHeader = "";
switch (tabNumber)
{
case 1:
tabHeader="Top Attractions to See";
break;
case 2:
tabHeader="Do This";
break;
case 3:
tabHeader="Stay Here";
break;
case 4:
tabHeader="Enjoy This";
break;
}
textView.setText(tabHeader);
RecyclerView bookedRecycler =(RecyclerView)rootView.findViewById(R.id.bookedRecycler);
RecyclerView vendorRecycler =(RecyclerView)rootView.findViewById(R.id.vendorRecycler);
RecyclerView.LayoutManager vendorLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false);
RecyclerView.LayoutManager bookedLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false);
vendorRecycler.setLayoutManager(vendorLM);
bookedRecycler.setLayoutManager(bookedLM);
VendorAdapter venAdapter = new VendorAdapter();
vendorRecycler.setAdapter(venAdapter);
BookedAdapter bookAdapter = new BookedAdapter();
bookedRecycler.setAdapter(bookAdapter);
return rootView;
}
Doing this this way gives me an
"Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.iconiccode.where/com.iconiccode.where.fragments.HomeFragment}; have you declared this activity in your AndroidManifest.xml?"
I have read that there is no need to declare fragments but even after declaring them I still have the same issues. I'm not entirely sure I'm even going about this the correct way
You are populating the fragment in a wrong way
Intent intent = new Intent(getApplicationContext(),HomeFragment.class);
startActivity(intent);
This is the way to initialize activity not the fragment you can look at this tutorial , provided link will explain the process you need to follow for populating a fragment in your activity
Related
Here the code:
SectionsPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#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);
Fragment fragment = null;
switch(position){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
PlaceholderFragment:
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private PageViewModel pageViewModel;
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = new ViewModelProvider(this,
new ViewModelProvider.NewInstanceFactory()).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container, false);
final TextView textView = root.findViewById(R.id.section_label);
pageViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
Using tabbed activity from android studio example whit legacy android studio libraries
I would like to add icons above the writing, please write some examples thanks.
To add an icon above the text in TabLayout you can use the attribute android:icon of TabItem. More information can be found in the Material Design Documentation. The app:tabIconTint is responsible to set the icon tint color.
An a example in xml is like below:
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabIndicatorHeight="2dp"
app:tabMode="fixed"
app:tabIconTint="#android:color/white"
app:tabTextColor="#android:color/white">
<com.google.android.material.tabs.TabItem
android:id="#+id/tabItem1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_home_24dp"
android:text="Tab1" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_chat_24dp"
android:text="Tab2" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_create_24dp"
android:text="Tab3" />
</com.google.android.material.tabs.TabLayout>
or Programmatically:
TabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home_24dp);
Result:
This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 6 years ago.
(I already posted a question about this problem that got deleted. I am sorry if I didn't explained my problem good enough. Also I am a german person so forgive me if my english isn't very good.)
I really tried a lot of things to get this simple program to work. I think that the solution to this will be very simple but first you need to find it...
I tried three different ways to code this and ended up with this one based on this Tutorial:
Define the Variable
String[] list = {"One", "Two", "Three"};
Creating the Adapter
ListAdapter Adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
Cast the ListView into the View
ListView mainList1 = (ListView) findViewById(R.id.mainList1);
Set the Adapter (wish causes the problem)
mainList1.setAdapter(Adapter1);
So everytime I am trying to set the Adapter the Program throws out a java.lang.NullPointerException. As I already said I tried a lot of things to get this program to work. This is why I now need the help of the StackOverflow-Comunity. I am trying to explain this problem as good as I can so maybe one day I can finish my project...
These information's might also be relevant to this:
Full MainActivity.java (Original):
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
String[] Vertretung1 = {
"1. Stunde | Frie [Ku] --› Eshk [Et Raum 008]",
"2. Stunde | Frie [Ku] --› Eshk [Et Raum 008]",
"3. Stunde | Frie [Ku] --› Eshk [Et Raum 008]"
};
String[] Vertretung2 = {
"1. Stunde | Grok [Ma] --› Grot [De Raum 111]",
"2. Stunde | Grok [Ma] --› Grot [De Raum 111]",
"3. Stunde | Grok [Ma] --› Grot [De Raum 111]"
};
ListAdapter Adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Vertretung1);
ListView mainList1 = (ListView) findViewById(R.id.mainList1);
mainList1.setAdapter(Adapter1); //Causes the Problem
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
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 static class FragmentOne extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_one, container, false);
return rootView;
}
}
public static class FragmentTwo extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_two, container, false);
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "HEUTE";
case 1:
return "MORGEN";
}
return null;
}
}
}
Full activity_main.xml (Original):
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="me.muehl.cvovertretungsplan.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Full `fragment_main_one.xml` *(Original)*: [link][2]
Thanks for reading ;)
You must move all ListView things into the Fragment class instead of the activity since that is where you've defined the ListView in the XML.
ListView mainList1 = (ListView) findViewById(R.id.mainList1);
That line will search only in the layout you've used in setContentView.
In order to move the ListView in the Fragment, you can find this line
View view = inflater.inflate...
And get the ListView with the next lines containing...
ListView lv = view.findViewById(...);
// TODO: setAdapter
return view;
I have made a recyclerview in my app.
The problem is that I'm getting the following error: java.lang.IllegalStateException: RecyclerView has no LayoutManager even when I've defined it.
Here's ListContentAAR.java file's code:
class ListContentAAR {
String picTag;
ListContentAAR( String picTag) {
this.picTag = picTag;
}
}
Here's RVAdapterAAR.java file's code:
public class RVAdapterAAR extends RecyclerView.Adapter<RVAdapterAAR.PersonViewHolder> {
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView pic;
PersonViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.card_accept_request);
homelessPic = (TextView) itemView.findViewById(R.id.pic_tag);
}
}
List<ListContentAAR> listContentAARs;
RVAdapterAAR(List<ListContentAAR> listContentAARs) {
this.listContentAARs = listContentAARs;
}
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_accept_a_request, viewGroup, false);
PersonViewHolder personViewHolder = new PersonViewHolder(view);
return personViewHolder;
}
public void onBindViewHolder (PersonViewHolder personViewHolder, int i) {
personViewHolder.pic.setText(listContentAARs.get(i).homelessPicTag);
}
public int getItemCount() {
return listContentAARs.size();
}
}
Here's AcceptARequest.java file's code:
public class AcceptARequest 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;
private OnFragmentInteractionListener mListener;
private List<ListContentAAR> listContentAARs;
private RecyclerView recyclerView;
public AcceptARequest() {
// Required empty public constructor
}
/**
* 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 AcceptARequest.
*/
// TODO: Rename and change types and number of parameters
public static AcceptARequest newInstance(String param1, String param2) {
AcceptARequest fragment = new AcceptARequest();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#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
View rootView = inflater.inflate(R.layout.fragment_accept_a_request, container, false);
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.accept_request_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData(){
listContentAARs = new ArrayList<>();
listContentAARs.add(new ListContentAAR("Emma Wilson"));
}
private void initializeAdapter(){
RVAdapterAAR adapter = new RVAdapterAAR(listContentAARs);
recyclerView.setAdapter(adapter);
}
// 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
void onFragmentInteraction(Uri uri);
}
}
Here's fragment_accept_a_request.xml file's code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.abc.xyz.AcceptARequest">
<android.support.v7.widget.RecyclerView
android:id="#+id/accept_request_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v7.widget.CardView
android:id="#+id/card_accept_request"
android:layout_width="match_parent"
android:layout_height="#dimen/card_accept_request"
app:cardElevation="2dp"
app:cardUseCompatPadding="true"
app:contentPadding="10dp">
<!--<ImageView
android:id="#+id/pic_accept"
android:layout_width="match_parent"
android:layout_height="#dimen/pic_dimen_accept"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_alignParentTop="true"/> -->
<TextView
android:id="#+id/pic_tag"
android:layout_width="match_parent"
android:layout_height="#dimen/pic_dimen_accept"
android:text="#string/image_view_tag_accept"
android:gravity="center_horizontal|center_vertical"/>
</android.support.v7.widget.CardView>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Here's MainActivity.java file's code:
public class MainActivity extends AppCompatActivity {
/**
* 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}.
*/
public SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface typeFace = Typeface.createFromAsset(getAssets(),"fonts/Pacifico.ttf");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setTypeface(typeFace);
toolbar.setTitle(mTitle.getText().toString());
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsIntent);
} else if (id == R.id.action_profile) {
Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileIntent);
} else if (id == R.id.action_send_feedback) {
Intent sendFeedbackIntent = new Intent(MainActivity.this, SendFeedback.class);
startActivity(sendFeedbackIntent);
} else if (id == R.id.action_help) {
Intent helpIntent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(helpIntent);
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#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 MainActivity.PlaceholderFragment.newInstance(position + 1);
switch (position) {
case 0:
return new AcceptARequest();
case 1:
return new PostARequest();
default:
return new AcceptARequest(); // return AcceptARequest() actually
}
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Accept A Request";
case 1:
return "Post A Request";
}
return null;
}
}
/**
* 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);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Here's the stacktrace:
FATAL EXCEPTION: main
java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.support.v7.widget.RecyclerView.generateLayoutParams(RecyclerView.java:3182)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at com.humanehelper.humanehelper.AcceptARequest.onCreateView(AcceptARequest.java:75)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:610)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:677)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
at android.view.View.measure(View.java:15172)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1848)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1273)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com
As I'm a beginner, I'm unable to figure out why am I getting the following error.
Please let me know.
Thanks in advance.
Remove the child elements from your RecyclerView in your fragment_accept_a_request layout.
You add children to your recycler views with the adapter, not via nested XML elements.
The problem is that when the layout inflation tries to add those children you've declared in your XML the parent RecyclerView is not yet fully configured to have children.
I got it!
The problem was in two files.
First problem as stated by laalto was in fragment_accept_a_request.xml. Removing the XML elements from recyclerView & placing it below it but in the same parent layout did the job.
Second problem was in AcceptARequest.java. Here I was declaring two RecyclerView one for initialiseData() method & another for declaring the recyclerView.
The changes I made in fragment_accept_a_request.xml is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.abc.xyz.AcceptARequest">
<android.support.v7.widget.RecyclerView
android:id="#+id/accept_request_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.CardView
android:id="#+id/card_accept_request"
android:layout_width="match_parent"
android:layout_height="#dimen/card_accept_request"
app:cardElevation="2dp"
app:cardUseCompatPadding="true"
app:contentPadding="10dp">
<!--<ImageView
android:id="#+id/pic_accept"
android:layout_width="match_parent"
android:layout_height="#dimen/pic_dimen_accept"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_alignParentTop="true"/> -->
<TextView
android:id="#+id/pic_tag"
android:layout_width="match_parent"
android:layout_height="#dimen/pic_dimen_accept"
android:text="#string/image_view_tag_accept"
android:gravity="center_horizontal|center_vertical"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
I am pretty new to Android. I am making a new App which makes use of Tabs.
Now, I want to display different fragments in the tabs.
Please note that my MinSDK is Android KitKat 4.4 so I wont be using deprecated methods
My Code is:
MainActivity.java
public class MainActivity extends ActionBarActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
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 activity.
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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.search)
{
Toast.makeText(getApplicationContext(),"You tapped on SEARCH !", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
}
#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 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;
}
}
/**
* 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_1, container, false);
Button b1 = (Button) rootView.findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Done", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
}
Fragment_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<EditText
android:id="#+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter your Name (Fragment Main"/>
<EditText
android:id="#+id/et2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et1"
android:hint="Enter your ID (Fragment Main)"/>
<Button
android:id="#+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="#+id/et2"/>
</RelativeLayout>
Fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$FragmentOne">
<Button
android:id="#+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="#+id/et2"/>
</RelativeLayout>
I have changed the tools:context in fragment_1.xml for my tests. I don't know what it does
Now, when the user opens the App, he should see the Fragment_Main fragment. When he swipes for the next tab, he should see fragment_1.
Please help in detail as i am very new.
So what exactly doesn't work?
I can only guess, but you don't use Fragment_Main.xml anywhere.
You are already passing position of view pager to your fragment, you should retrieve it and inflate layout based on it. Something like this inside your fragment:
private int mFragmentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mFragmentIndex = getArguments().getInt(ARG_SECTION_NUMBER);
}
}
and in onCreateView you should inflate different layout based on fragment index:
View rootView;
if (mFragmentIndex == 1) {
rootView = inflater.inflate(R.layout.Fragment_Main, container, false);
} else {
rootView = inflater.inflate(R.layout.fragment_1, container, false);
}
Anyway, I would suggest using different fragments, instead of inflating different layouts. Something like this:
#Override
public Fragment getItem(int position) {
if (position == 0) {
return MainFragment.newInstance();
} else {
return SomeOtherFragment.newInstance();
}
}
I have a MainActivity which is a ActionBarActivity with viewPager inside.
Then I have 3 pages.
In the first page there is a tableLayout with tableRow clickListener (inside blocks) from where I would like to start an intent to another layout without hiding TabBar. Here is my code:
MainActivity.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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;
}
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 FirstFragment (defined as a static inner class below).
//return FirstFragment.newInstance(position + 1);
switch(position) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#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 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;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class FirstFragment 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.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.first_fragment, container, false);
createTable(rootView);
return rootView;
}
public static FirstFragment newInstance(String string) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString("msg", "PROVA 1");
fragment.setArguments(args);
return fragment;
}
void createTable(View rootView){
TableLayout ll = (TableLayout) rootView
.findViewById(R.id.tableLayout);
String categorie[];
// MyDatabase db=new MyDatabase(getActivity().getApplicationContext());
// db.open(); //apriamo il db
MyDatabase db = new MyDatabase(getActivity().getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
db.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c=db.fetchCategorie(); // query
//startManagingCursor(c);
//qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview
int categoriaColumn=c.getColumnIndex(MyDatabase.CategorieMetaData.PRODUCT_CATEGORIA_KEY); //indici delle colonne
//int priceCol=c.getColumnIndex(MyDatabase.ProductsMetaData.PRODUCT_PRICE_KEY);
ArrayList<String> categorieList = new ArrayList<String>();
if(c.moveToFirst()){ //se va alla prima entry, il cursore non è vuoto
do {
categorieList.add(c.getString(categoriaColumn)); //add to arraylist
//productsTv.append("Product Name:"+c.getString(nameCol)+", Price:"+c.getInt(priceCol)+"\n"); //estrazione dei dati dalla entry del cursor
//Log.d("Prova", "PROVA:"+ "Product Name:"+c.getString(categoriaColumn)+", Price:"+c.getInt(priceCol)+"\n");
} while (c.moveToNext());//iteriamo al prossimo elemento
}
db.close();
categorie = categorieList.toArray(new String[categorieList.size()]);
for (int i = 0; i < categorie.length; i++) {
TableRow tbRow = new TableRow(getActivity().getApplicationContext());
tbRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView tv1 = new TextView(getActivity().getApplicationContext());
tv1.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
tbRow.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
ImageView imageView = new ImageView(getActivity().getApplicationContext());
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
tv1.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv1.setId(i);
tv1.setText(categorie[i]);
tv1.setTextColor(Color.parseColor("#000000"));
tbRow.addView(imageView);
tbRow.addView(tv1);
ll.addView(tbRow, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
final String finalCategorie[] = categorie;
final int finalI = i;
final View finalRootView = rootView;
tbRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Intent newIntent = new Intent(MainActivity.this, detailActivity.class);
// newIntent.putExtra("key", strings[finalI]);
Log.d("TEST", "Row selected: " + finalCategorie[finalI]);
// startActivity(newIntent);
// Intent intent = new Intent(getActivity(), EventiFragment.class);
// startActivity(intent);
}
});
}
}
}
public static class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String string) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
public static class ThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentThird);
tv.setText(getArguments().getString("msg"));
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 3");
f.setArguments(b);
return f;
}
}
public static class EventiFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.eventi_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentEventi);
tv.setText(getArguments().getString("msg"));
return v;
}
public static EventiFragment newInstance(String string) {
EventiFragment f = new EventiFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
}
first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="#string/main_photo_description"
android:scaleType="centerCrop"
android:src="#drawable/main_photo" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TableLayout>
</LinearLayout>
</ScrollView>
eventi_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/FragmentEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textSize="26sp"/>
So I would create a separate layout, but instead of putting the layout in two separate XML files, put it all in one. For example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/intent_replacement"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Here's the stuff for the supposed intent -->
</RelativeLayout>
</RelativeLayout>
So in this you can have one attribute called visible then programmatically you just get the Layout as an object and when an item in the table is clicked on use intentLayoutObject.setVisibility(true)
Likewise when you get back button pressed intentLayoutObject.setVisibility(false)