using differnet Fragements with the same layout inside a ViewPager - android

in my app i have a ViewPager with pages where each of them show a list. when i started i directly added the ListFragement to the ViewPager. in order to change the layout of each page (for example adding a ViewText below each list) i later created a fragement with an own layout file that contains this listFragement, which i add to the ViewPager
this is how this layout (for each page looks)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab_history"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/tab_fragment"
android:layout_width="match_parent"
android:layout_height="0sp"
android:layout_weight="1" >
</FrameLayout>
<LinearLayout
android:id="#+id/message_canvas"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/lightgreen"
android:orientation="horizontal"
android:paddingBottom="6sp"
android:paddingTop="6sp"
android:visibility="visible" >
<TextView
android:id="#+id/message"
android:layout_width="0sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:contentDescription="#string/emptyString"
android:gravity="center_horizontal"
android:text="#string/emptyString"
android:textAlignment="center"
android:textColor="#color/green"
android:textStyle="bold" />
</LinearLayout>
this is the layout for the ViewPager
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white" >
</android.support.v4.view.ViewPager>
this is how i add each of the ListFragement to its parent Fragement (with the same layout) (in this case the contact list)
public class FragmentTabContacts extends FragmentTab{
#Override
protected Fragment getFragment() {
return new ListFragmentContactlist();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.fragment = getFragment();
View view = inflater.inflate(R.layout.tab_fragement, null);
messageCanvas = (ViewGroup)view.findViewById(R.id.message_canvas);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.tab_fragment, this.fragment);
fragmentTransaction.commit();
return view;
}
}
this is the adapter for the ViewPager
public class FragmentAdapter extends FragmentPagerAdapter {
/**
* list of {#link NinjaListFragment} used for all tabs
*/
private List<ITabContainer> fragments;
public FragmentAdapter(FragmentManager fm, List<ITabContainer> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public Fragment getItem(int position) {
return (Fragment) fragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return fragments.indexOf(object);
}
}
and this is the method i wrote inside the ViewPager to set the new Fragements to it and also the corresponsing tabs
/**
* adds the {#link ViewGroup} representing the tab to the {#value #mapTabs} for generating the tabs
* #param inflater the {#link LayoutInflater} used to inflate the tab
* #param tabs the {#link ViewGroup} containing the inflated tabs.
* #param tabContainer the fragment with the interface {#link ITabContainer} used as content for the tab added to {#link #fragments}
* #param imageId the id of the image to be shown on the tab
* #param onClickListener the {#link View.OnClickListener} to receive the tab clicks
*/
private void addTab(LayoutInflater inflater, ViewGroup tabs, ITabContainer tabContainer, int imageId, View.OnClickListener onClickListener) {
inflater.inflate(R.layout.main_tab, tabs);
int index = tabs.getChildCount() - 1;
ImageView ivTab = (ImageView) tabs.getChildAt(index);
ivTab.setTag(String.valueOf(index));
ivTab.setImageResource(imageId);
ivTab.setOnClickListener(onClickListener);
mapTabs.put(index, ivTab);
fragments.add(tabContainer);
}
and this is how i call this method in the onCreate method of the ViewPager
addTab(inflater, vgTabs, new FragmentTabContacts(), R.drawable.ic_tab_contacts, onClickListener);
addTab(inflater, vgTabs, new FragmentTabHistory(), R.drawable.ic_tab_history, onClickListener);
addTab(inflater, vgTabs, new ListFragmentGroups(), R.drawable.ic_tab_groups, onClickListener);
addTab(inflater, vgTabs, new FragmentTabFavorits(), R.drawable.ic_tab_favorits, onClickListener);
because naturally all of the fragements with the same layout contain the same id (android:id="#+id/tab_fragment") for the Framelayout where i add the ListFragement, it seems that the ViewPager has a problem identifying each of them. i only completed the first 2 pages that way (the 4th tab contains another ViewPager and this works), but the result is that the first page shows now the content of the second one, while the second page is empty.
i want to have a seperate TextView for each page because i want to store different text inside each page, and i dont want to copy the same layout (just with different ids) 4 times (in case there is no other solution for it).and i dont want to put that TextView inside the main PageView layout and refresh the content after each tab switch.
what can i do to reuse the same layout for each ListFragement of each page?

meanwhile i found a simple workaround. i created 4 different layouts (with 4 different ids for the fragement) for all 4 pagesand include the same redundant parts in each of them
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/list_history"
android:name="at.happyninja.addressbook.fragments.ListFragmentHistory"
android:layout_width="match_parent"
android:layout_height="0sp"
android:layout_weight="1" />
<include layout="#layout/tab_message" />
<include layout="#layout/tab_keyboardview" />

Related

Fragment Question, where to build buttons etc

I am using fragments to update a text view I have so when the person clicks a button the text view moves on to the next question. I'm not sure if I am doing the correct work in one fragment instead of the other. My current screen looks like this:
I will probably have to add some more buttons/widgets to this but should I be adding it into the XML for the fragment or the fragment container?
Here is XML for fragment actions:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_question_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".FragmentActions"
>
<!-- this is where fragments will be shown-->
<FrameLayout
android:id="#+id/question_container1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:scaleType="centerInside" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/questions_yes1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/yes" />
<Button
android:id="#+id/questions_no1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/no" />
</LinearLayout>
</LinearLayout>
And here is the fragment details:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/button_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
tools:context=".FragmentDetails">
<!--Blank Fragment Layout-->
<TextView
android:id="#+id/questions_text_view1"
android:layout_width="match_parent"
android:layout_height="91dp"
android:gravity="center"
android:textAlignment="center"
/>
</FrameLayout>
Updated FragmentDetails
public class FragmentDetails extends Fragment {
private final String TAG = getClass().getSimpleName();
private List<Integer> mQuestionIds;
private int mListIndex;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
//Get a reference to the textView in the fragment layout
final TextView textView = (TextView) rootView.findViewById(R.id.questions_text_view1);
if (mQuestionIds != null) {
textView.setText(mQuestionIds.get(mListIndex));
//Increment the position in the question lisy as long as index is less than list length
if (mListIndex < mQuestionIds.size() - 1) {
mListIndex++;
setmQuestionIds(QuestionList.getQuestions());
setmListIndex(mListIndex);
} else {
//end of questions reached
textView.setText("End of questions");
}
//Set the text resource to display the list item at that stored index
textView.setText(mQuestionIds.get(mListIndex));
}
else {
//Log message that list is null
Log.d(TAG, "No questions left");
}
//return root view
return rootView;
}
public void setmQuestionIds (List < Integer > mQuestionIds) {
this.mQuestionIds = mQuestionIds;
}
public void setmListIndex ( int mListIndex){
this.mListIndex = mListIndex;
}
}
Fragment Actions activity
public class FragmentActions extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_actions);
Button yes = findViewById(questions_yes1);
// Only create new fragments when there is no previously saved state
if (savedInstanceState == null) {
//Create Question Fragment
final FragmentDetails fragmentDetails = new FragmentDetails();
fragmentDetails.setmQuestionIds(QuestionList.getQuestions());
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the list of question Ids for the head fragent and set the position to the second question
//Fragment manager and transaction to add this fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.question_container1, fragmentDetails)
.commit();
}
});
}
}
}
If your Buttons remain the same while the TextView changes, you may add your Buttons to the fragment container.
Remember that, your fragments will be presented inside the FrameLayout of the fragment container. You gotta keep your Buttons, outside the FrameLayout.
Or if you want to have different Buttons for different fragments (Questions, in your case), you can also add the Buttons to the fragments. But in that case, you gotta add them separately to each of the fragments.
I guess there's no right answer to your question. You could try different approaches.
Maybe you could implement the buttons in the fragment container, as #smmehrab pointed out. I see this as a more difficult solution, because when you click on an item from the container you can manage the views of the container, not the fragment's views. You would get NullPointer if I recall correctly. This happens because the context when the button is clicked in the fragment container is different than the context when clicking from within the fragment. So you should implement an interface on the fragment container that listens to clicks, and the fragment catches the click. You could do this, and I actually am doing it in my current app, but I have no choice.
You could instead use Motion Layout (which extends from Constraint Layout) as the root view of your fragment, instead of CardView. This way you could set all the fragment's views with a flat hierarchy (flat hierarchies improves rendering time, so that's an improvement, and you can use CardView as one child) and set the buttons right there, in the Motion Layout (remember, the motion layout would be the fragment's root view). You could set the click listener right there and implement animations between different textViews.
I'm sure there are plenty of other solutions, take this only as a contribution.
If you're unfamiliar with Motion Layout you can just google it, android official documentation about it is great.

How to replace an Android fragment with another fragment inside a ViewPager?

I have a view pager consisting of 4 tabs. Each tab holds its own fragment.
How would I be able to use fragment transaction to replace the fragment in tab 3 with a new fragment?
I've tried a lot of things, but I have not been able to come up with a solution at all. I've tried looking around on google and stackoverflow, but with no success.
I assume that your fragment has a button that is put in the center. By clicking on it, you can change the layout stays under of this button. The content/layout of the first fragment you mentioned should be replaced with wrapperA and the content/layout of the second one should be replaced with wrapperB. I put a simple red background for wrapperA to distinguish it with wrapperB, wrapperB is also green due to the same reason. I hope this is what you want:
public class SwitchingFragment extends Fragment {
Button switchFragsButton;
RelativeLayout wrapperA, wrapperB;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.layout_switch, container, false);
wrapperA = (RelativeLayout) rootView.findViewById(R.id.wrapperA);
wrapperB = (RelativeLayout) rootView.findViewById(R.id.wrapperB);
switchFragsButton = (Button) rootView.findViewById(R.id.switchFragsButton);
switchFragsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (wrapperB.getVisibility() == View.GONE) {
wrapperB.setVisibility(View.VISIBLE);
// There is no need to change visibility of wrapperA since it stays behind when wrapperB is visible.
// wrapperA.setVisibility(View.GONE);
}
else {
wrapperB.setVisibility(View.GONE);
// Again, there is no need.
// wrapperA.setVisibility(View.VISIBLE);
}
}
});
return rootView;
}
}
The layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<!-- The content of first fragment should be in "wrapperA". -->
<RelativeLayout
android:id="#+id/wrapperA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/red"
android:visibility="visible">
</RelativeLayout>
<!-- The content of second fragment should be in "wrapperB". -->
<RelativeLayout
android:id="#+id/wrapperB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"
android:visibility="gone">
</RelativeLayout>
<!-- As I said, I assume that the layout switcher button is stable
and so it should be in front of the switching layouts. -->
<Button
android:id="#+id/switchFragsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#color/black"
android:text="Switch"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/white"/>
</RelativeLayout>
Alternatively, you can try to change the fragment directly by notifying your FragmentPagerAdapter as described in this link:
Replace fragment with another fragment inside ViewPager

Android adding Fragment inside Fragment

Hi there (and thanks in advance),
I have an application with a Google Play Store-like layout (using PagerTabStrip with 5 sub fragments). In some of those fragments I will need to display a little info regarding the last time the data was updated.
I immediately thought of creating a fragment (LastUpdatedFragment) which I would then add (nest) to the fragments I needed. At first, and since the last updated date was supposed to be the same for every screen, things were working (I simply added the fragment in the xml of the parent Fragments I needed and inside onCreateView I would put the date in the TextView), but after some changes I now need to send a specific date for each one of these LastUpdatedFragment instances.
I came up with one way - creating new custom attributes for my Fragment and then I would set the date I wanted. After some reading I stumbled across a easier way (Fragments within Fragments - dinamically adding the fragment using FragmentManager) - I simply needed the parent Fragment to handle the input parameters and pass it to the child fragment.
The problem is that, although I get no errors I also get no child fragment, it just does not display. I would be grateful if you could guide me in the right direction.
ScoreBoardFragment.java -> Parent Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_scoreboard, container,
false);
for (int i = 0; i < tvCount; i++) {
tvName = "f_scoreboard_header_tv" + String.valueOf(i);
resID = getResources().getIdentifier(tvName, "id",
_activity.getPackageName());
header = (TextView) rootView.findViewById(resID);
header.setTypeface(MyGlobalConfig.getInstance().getHeadersFont());
}
FragmentManager childFragMan = getChildFragmentManager();
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
LastUpdatedFragment fragB = new LastUpdatedFragment();
childFragTrans.add(R.id.FRAGMENT_PLACEHOLDER, fragB);
childFragTrans.addToBackStack("B");
childFragTrans.commit();
return rootView;
}
fragment_scoreboard.xml (simplified but displaying everything else)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/FRAGMENT_PLACEHOLDER"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
style="#style/ListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/f_scoreboard_header_tv0"
style="#style/ListViewRowHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#" />
</LinearLayout>
<ListView
android:id="#+id/f_scoreboard_lvbody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true" >
</ListView>
</LinearLayout>
LastUpdatedFragment.java -> Child Fragment
public class LastUpdatedFragment extends Fragment{
private View rootView;
private TextView tv;
private Context ctx;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(
getActivity()));
this.ctx = getActivity().getApplicationContext();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_date, container,
false);
tv = (TextView) rootView.findViewById(R.id.f_date_tv);
tv.setTypeface(MyGlobalConfig.getInstance().getBodyFont());
tv.setText(getString(R.string.lastupdated) + ": " + Util.getLastUpdated(ctx));
return rootView;
}
}
fragment_date.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/f_date_tv"
style="#style/LastUpdatedTV"
android:layout_width="match_parent"
android:text="Data de última actualização: 27/12/2014 21:30" />
</LinearLayout>
Try to use FrameLayout instead of LinearLayout as Placeholder.

How to build a viewpager that acts infinite and detects which side it was swiped?

I understand that a viewpager can be used, but I am having a hard time finding a good resource explaining how to use a viewpager with the following additions.
The view to record if the swipe was left or right, and either way just reload a new content (if left I want it to record no, right for it to record yes).
I want it to be infinite or really large, like 10000.
Finally, be able to add buttons underneath it as well.
In summary any direction, tutorials, or examples would be appreciated.
no tabs - just avoided implementing a tab listener and including tabs when creating the view pager
read swipes
load new content
infinite or really large
have buttons underneath it - done by including it in the drawer layout
Hopefully this clears things up:
UPDATE:
Here is the scenario I am trying to read swipes - if left record no and if right record yes, then grab new content from cache and display it, with the same two swipe options, I was thinking maybe I can just have 3 "pages" and swiping left records the action then it resets to position (middle - 1) and then loads the next content available in the cache... the only thing is I do not know how to call the reset and ask for a refresh of the content...
EDIT:
No tabs has been solved by just adding the code like so:
//viewpager adapter
private PageAdapter mAdapter;
private ViewPager viewPager;
// Initializing pager - in On Create
viewPager = (ViewPager) findViewById(R.id.random_pager);
FragmentManager fm = getFragmentManager();
mAdapter = new PageAdapter(getSupportFragmentManager(), new UserCreatedFragment(), new UserUpVotesFragment(),new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
// Here you would declare which page to visit on creation
viewPager.setCurrentItem(1);
This is the adapter:
public class PageAdapter extends FragmentPagerAdapter{
private Fragment frag1;
private Fragment frag2;
private Fragment frag3;
public PageAdapter(FragmentManager fm, Fragment frag1, Fragment frag2, Fragment frag3) {
super(fm);
this.frag1 = frag1;
this.frag2 = frag2;
this.frag3 = frag3;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
//fragments should record no and reset to the same frag with new content back in position 1
return frag2;
case 1:
//fragments for activity
return frag2;
case 2:
//fragments should record yes and reset to the same frag with new content back in position 1
return frag2;
}
return null;
}
//return count for number of tabs/swipes
#Override
public int getCount() {
return 3;
}
}
xml of activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
<!--View pager inside drawer so when opens it displays -->
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:id="#+id/viewPageLinear">
<android.support.v4.view.ViewPager
android:id="#+id/random_pager"
android:layout_width="wrap_content"
android:layout_height="300dp">
</android.support.v4.view.ViewPager>
<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:gravity="center"
android:id="#+id/no"
android:layout_below="#+id/viewPageLinear"/>
<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:gravity="center"
android:layout_below="#+id/no"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
xml of fragment loaded:
<?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">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:gravity="center"
android:layout_alignParentTop="true"
android:id="#+id/imagehere"/>
</RelativeLayout>
It's recommended to use FragmentStatePagerAdapter instead of FragmentPagerAdapter.
See http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html for reference.
This version of the pager is more useful when there are a large number
of pages, working more like a list view.
Other than that, it's not quite clear to me what the question (or the problem) is.
If you want to have Tabs title in your ViewPager you have to add this inside your ViewPager.
<android.support.v4.view.ViewPager
android:id="#+id/random_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.PagerTitleStrip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top" />
</android.support.v4.view.ViewPager>
And if you want infinite Tabs you should use FragmentStatePagerAdapter that is recommended when the number of Tabs is not specified.
Edit...
I've been looking a solution to your problem and this is what i found, if you want to know what direction user swiped you can do it this way, Implement SimpleOnPageChangeListener and on onPageSelected method do this:
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter, final int oldPosition, final int newPosition) {
if (oldPosition>newPosition){
// left to right
}
else{
//right to left
}
}

Listview as a detail fragment in master/detail view

Am creating a master/detail fragment from this link. This works fine, now here instead of textview in detail fragment class i would like to implement listviews, (ie) i would like to display the details of the masterview as a child listview, hence i tried
detail.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:id="#+id/listview1"
/>"
<ListView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:id="#+id/listview2"
/>"
</LinearLayout>
and in my detailFragment class
public class DetailFragment1 extends ListFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] values = new String[] { "1", "2", "3",
"4" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
My problem is child listview is displaying at initial stage but i want to display this listview when i click the first row of master page.Am new to fragments, so help me in achieving this. Thanks in advance..
Create a CallBack interface:
public interface Callbacks {
public void onItemSelected(long id);
}
Let the fragment inplement it:
public class DetailFragment1 extends ListFragment implements CallBacks {
In the ListFragment OnListitemClick:
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
mCallbacks.onItemSelected(id);
}
In the Activity:
Public class MyActivity extends FragmentActivity implements Callbacks {
#Override
public void onItemSelected(long id) {
// Replace the detail fragment with the corresponding item selected in the list
}
Instead of doing like this, you can design a layout which contains ListView as master and frameLayout container. In frameLayout container, you can dynamically inflate layout, which is designed in such a way that you can have child listview and details view.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".NavigationActivity" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="#color/strip_background"
android:layout_weight="1"
android:orientation="vertical" >
<ListView
android:id="#+id/nav_lv_transactions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none" >
</ListView>
</LinearLayout>
<FrameLayout
android:id="#+id/nav_fl_frag_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="14"
android:background="#android:color/darker_gray" >
</FrameLayout>
</LinearLayout>
In onclick listerner put this code,
Bundle arguments = new Bundle();
arguments.putString(ARG_ITEM_ID,
"Some Name");
MyClassFragment newFragment = new MyClassFragment();
newFragment.setArguments(arguments);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_fl_frag_container, newFragment);
transaction.commit();
Try this. It will work

Categories

Resources