I have following two Fragment containing TextView and Button:
public class MyFragmentText extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final MyFragmentText newInstance(String message)
{
MyFragmentText f = new MyFragmentText();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.layout_text, container, false);
TextView messageTextView = (TextView)v.findViewById(R.id.textView);
messageTextView.setText(message);
return v;
}
}
and
public class MyFragmentButton extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final MyFragmentButton newInstance(String message)
{
MyFragmentButton f = new MyFragmentButton();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.layout_button, container, false);
TextView messageTextView = (TextView)v.findViewById(R.id.textView);
messageTextView.setText(message);
return v;
}
}
and I have three XML files that are:
Main layout:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Button layout
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button"
android:width="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here"/>
</RelativeLayout>
Textview 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:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Now when I am calling them from Main program to show sliding windows with the following code, it works nicely.
public class PageViewActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
//btn = (Button) findViewById(R.id.button);
//btn.setText("Hello World!!!");
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragmentButton.newInstance("Fragment 1"));
fList.add(MyFragmentText.newInstance("Fragment 2"));
return fList;
}
private class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
}
but if I apply
btn = (Button) findViewById(R.id.button);
btn.setText("Hello World!!!");
it gives me Null pointer exception. I guess it's due the the fact that thet lauyout is not inflated when I am calling the btn. I would appreciate if anyone could suggest any solution.
As far as i undesrtand activity_page_view xml is this:
<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.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
This layout has no elemnt with button, that's why btn = (Button) findViewById(R.id.button); returns null and btn.setText("Hello World!!!"); produces NPE
Related
I want to add dynamic tab items. I have a fragment which is FragmentOne and it has a TextView. I'm trying create FragmentOne in foreach and add to tabs. I tested code which is in setupViewPager but it doesn't work. How can I edit TextView which in fragments?
if I remove this lines it works but contents of fragment always show default that = "TAB ONE". I want to edit all TextView which is in fragments that created at run time;
View view = fView.getView();
TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
DynamicTabsActivity.java
public class DynamicTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int count = 10;
for (int i=0; i<count; i++){
OneFragment fView = new OneFragment();
View view = fView.getView();
TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
adapter.addFrag(fView,"TAB " + i);
}
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_dynamic_tabs.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<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/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
OneFragment.java
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
fragment_one.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"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">
<TextView
android:id="#+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
The fragment's layout hasn't been created at point that you call findViewById below:
OneFragment fView = new OneFragment();
View view = fView.getView();
TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
Following is more typically way this is coded:
public static class OneFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private int sectionNumber;
public OneFragment() {
}
public static OneFragment newInstance(int sectionNumber) {
OneFragment fragment = new OneFragment();
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_one, container, false);
sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
textView.setText("TAB " + sectionNumber);
return rootView;
}
}
you might also want to move fragment creation in to adapter...for example:
public Fragment getItem(int position) {
return OneFragment.newInstance(position + 1);
}
After trying for long...I came up with the following solution:
DynamicTabsActivity is my main activity, looks like this:
public class DynamicTabsActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private int noOfTabs = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(viewPagerAdapter);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
My fragment looks like this:
public class DynamicFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private int sectionNumber;
public DynamicFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
TextView textView = view.findViewById(R.id.txtTabItemNumber);
textView.setText("TAB " + sectionNumber);
return view;
}
public static DynamicFragment newInstance(int sectionNumber) {
DynamicFragment fragment = new DynamicFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
My ViewPager Class looks like this:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private int noOfItems;
public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
super(fm);
this.noOfItems = noOfItems;
}
#Override
public Fragment getItem(int position) {
return DynamicFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return noOfItems;
}
#Override
public CharSequence getPageTitle(int position) {
return "TAB "+(position+1);
}
}
DynamicTabsActivity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DynamicTabsActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<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/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.constraint.ConstraintLayout>
Fragment layout:
<?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"
tools:context=".DynamicFragment">
<TextView
android:id="#+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold" />
</RelativeLayout>
Hope it helps...
Try this,
LinearLayout main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView .setText("TAB " + i);
main .addView(textView );
this is image while useing keypad
and this image after keypad was hidden
I use EditText but below it there is ListView. After typing text inputs in EditText and then press done or click back to hide keypad. Then the part of ListView behind the keypad disappeared and replaced by white area (cleared), why ?
NOTE: this fragment is under tablayout and viewpager and the fragment which contain the edit text and listview is launched from the main fragment
this is main fragment
public class FriendsFragment extends Fragment {
public FriendsFragment() {
// Required empty public constructor
}
private FragmentActivity myContext;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.friends_fragment, container, false);
viewPager = (ViewPager) rootview.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootview.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
if (tab.getPosition() == 1) {
FindFriendsFragment.myfriends_list.invalidate(FindFriendsFragment.myfriends_list.getLeft(), FindFriendsFragment.myfriends_list.getTop(), FindFriendsFragment.myfriends_list.getRight(), FindFriendsFragment.myfriends_list.getBottom());
FindFriendsFragment.adapter.notifyDataSetChanged();
FindFriendsFragment.myfriends_list.clearFocus();
FindFriendsFragment.myfriends_list.postInvalidate();
}
}
});
TextView friends = (TextView) rootview.findViewById(R.id.search);
Typeface Exo_thin = Typeface.createFromAsset(myContext.getAssets(), "fonts/Exo2.0-Thin.otf");
friends.setTypeface(Exo_thin);
return rootview;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new MyFriendsFragment(), "My Friends");
adapter.addFragment(new FindFriendsFragment(), "Find Friends");
adapter.addFragment(new TwoFragment(), "Friend Requests");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
this is xml of main fragment
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/rel"
android:layout_alignParentTop="true"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="#+id/search"
android:text="Friends"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textSize="25sp"
android:textColor="#color/colorVeryDarkBlue"
/>
</RelativeLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabSelectedTextColor="#color/colorLightGreen"
app:tabTextColor="#color/colorDarkGreen"
app:tabMode="scrollable"
android:background="#color/colorDarkBlue"
app:tabIndicatorColor="#color/colorDarkBlue"
app:tabGravity="center"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
the fragment which contain listview and edit text
public class FindFriendsFragment extends Fragment {
public FindFriendsFragment()
{
// Required empty public constructor
}
ListView myfriends_list;
FindFriendsAdapter adapter;
ArrayList<FindFriends> arraylist ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootview= inflater.inflate(R.layout.find_friends_fragment, container, false);
EditText search=(EditText) rootview.findViewById(R.id.search);
Typeface Exo_Regular =
Typeface.createFromAsset(getActivity().getAssets(), "fonts/Exo2.0-
Regular.otf");
search.setTypeface(Exo_Regular);
arraylist = new ArrayList<FindFriends>();
arraylist.add(new FindFriends("mina fared", "hello
guys",1,"sdsdsdsds",true )) ;
adapter = new FindFriendsAdapter(getActivity(), arraylist);
myfriends_list.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootview;
}
}
And the related xml file is of the fragment which contain listview and edittext:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:background="#ffffff"
>
<LinearLayout
android:layout_height="60dp"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_marginTop="111dp"
android:id="#+id/refl"
android:background="#color/colorLightGrey"
android:layout_alignParentTop="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/search"
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"
android:background="#ffffff"
android:singleLine="true"
android:hint="Search"
android:ellipsize="start"
android:imeOptions="actionDone"
android:gravity="center_vertical|center_horizontal"
android:layout_marginTop="10dp"
android:textSize="15sp"
android:textColorHint="#color/colormyhintfindfiernds"
android:textColor="#color/colorDarkBlue"
/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:layout_marginTop="1dp"
android:layout_below="#+id/refl"
android:divider="#ffffff"
android:dividerHeight="1.5dp"
/>
</RelativeLayout>
this is the parent fragment which contains all fragments
public class ProfileFragment extends Fragment {
public ProfileFragment()
{
// Required empty public constructor
}
RelativeLayout rl1;
DrawView drawView ;
DrawView drawView2;
TextView myprofile,username,notification_txt,colloection_txt,friends_txt,setting_txt,public_profile_txt;
ImageView public_profile_btn,friends;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview=inflater.inflate(R.layout.myprofile_fragment, container,
false);
username= (TextView) rootview.findViewById(R.id.user_name_txt);
myprofile= (TextView) rootview.findViewById(R.id.myprofile);
notification_txt= (TextView) rootview.findViewById(R.id.notification_txt);
colloection_txt= (TextView) rootview.findViewById(R.id.colloection_txt);
friends_txt= (TextView) rootview.findViewById(R.id.friends_txt);
setting_txt= (TextView) rootview.findViewById(R.id.setting_txt);
public_profile_txt= (TextView) rootview.findViewById(R.id.public_profile_txt);
Typeface Exo_thin = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Exo2.0-Thin.otf");
Typeface Exo_SemiBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Exo2.0-SemiBold.otf");
myprofile.setTypeface(Exo_thin);
username.setTypeface(Exo_SemiBold);
notification_txt.setTypeface(Exo_SemiBold);
colloection_txt.setTypeface(Exo_SemiBold);
friends_txt.setTypeface(Exo_SemiBold);
setting_txt.setTypeface(Exo_SemiBold);
public_profile_txt.setTypeface(Exo_SemiBold);
ImageView x=(ImageView)rootview.findViewById(R.id.colloection);
ImageView y=(ImageView)rootview.findViewById(R.id.friends);
ImageView x1=(ImageView)rootview.findViewById(R.id.setting);
rl1 =(RelativeLayout)rootview.findViewById(R.id.rel2);
final View fragmentContainer = rootview.findViewById(R.id.container);
friends =(ImageView)rootview.findViewById(R.id.friends);
public_profile_btn=(ImageView)rootview.findViewById(R.id.public_profile);
public_profile_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment newFragment = new MyProfileFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(fragmentContainer.getId(), newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
friends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment newFragment = new FriendsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(fragmentContainer.getId(), newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
return rootview;
}
}
from manifest.xml search for your activity tag like this
<activity
android:name=".YourActivity"
android:label="#string/title_activity"
...>
</activity>
then add android:configChanges="keyboard|keyboardHidden" like that
<activity
android:name=".YourActivity"
android:configChanges="keyboard|keyboardHidden"
android:label="#string/title_activity"
...>
</activity>
EDIT
i found that my answer not completely right you may add
android:windowSoftInputMode="adjustNothing"
sorry about that
I'm working on an Application which contains a PageViewer inside a Layout.
But if i start it, the PageViewer isn't visible. (looks leight layout_height=0)
I never used a PageViewer inside other layouts, so maybe it isn't designed to be part of something?
Layout file (shortened,activity_tricks.xml):
<linearLayout>
<TableRow>
....
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrapt_content">
<android.support.v4.view.ViewPager
android:id="#+id/Activity_Trick_viewPager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="6dip" />
</TableRow>
<TableRow>
.
.
.
Trick_Fragment_layout.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:orientation="vertical" >
<TextView
android:id="#+id/trick_fragment_textView_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Activity:
public class TrickActivity extends FragmentActivity {
private ViewPager mViewPager;
private TrickActivityPageAdapter mPageAdapter;
public static final int FRAMES = 3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tricks);
mPageAdapter= new TrickActivityPageAdapter(getSupportFragmentManager(),frames);
mViewPager=(ViewPager)findViewById(R.id.Activity_Trick_viewPager);
mViewPager.setAdapter(mPageAdapter);
//... do other stuff.. //
}
}
public class TrickActivityPageAdapter extends FragmentPagerAdapter {
private int frames;
public TrickActivityPageAdapter(FragmentManager fm, int frames) {
super(fm);
this.frames = frames;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TrickFragment.init("F 1");
case 1:
return TrickFragment
.init("F 2");
case 2:
return TrickFragment.init("f3");
default:
return TrickFragment.init("default");
}
}
#Override
public int getCount() {
return frames;
}
}
public class TrickFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static Fragment init(String string) {
TrickFragment f = new TrickFragment();
Bundle bdl = new Bundle();
bdl.putString(EXTRA_MESSAGE, string);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.trick_fragment_layout, container, false);
TextView tv = (TextView)v.findViewById(R.id.trick_fragment_textView_1);
tv.setText(message);
return v;
}
I have successfully set up the a FragmentActivity with FragementPagerAdapter associated with ViewPager to implement two tabbed application .
One of the Tabs namely "Wave" has a text view and a button . All I want is call textview.setText method via the onClick method of button described by its xml attribute .
I do not know where should I initialize my TextView or Button , how can I get the context of Wave tab and where should I write onclick method-
public class InformationShow extends FragmentActivity {
XMLdata dataObject;
ViewPager viewPager;
PagerAdapter adpt;
Fragment temp;
TextView tv;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewPager=(ViewPager)findViewById(R.id.pager);
adpt = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adpt);
// temp=adpt.fg.findFragmentById((int)adpt.getItemId(1));
tv=(TextView)findViewById(R.id.graphWaveTextView);
bt = (Button)findViewById(R.id.button1);
}
public void changeText(View v){
tv.setText("It worked ");
}
Adapter Class
public class PagerAdapter extends FragmentPagerAdapter {
int count = 2;
CharSequence namme[] = {"Temperature","Wave"};
XMLdata data;
FragmentManager fg;
public PagerAdapter(FragmentManager fragmentManager ){
super(fragmentManager);
this.fg = fragmentManager;
}
Context context;
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:{
TemperatureGraphFrag temp = new TemperatureGraphFrag();
return temp;
}
case 1:{WaveHeightGraphFrag wave = new WaveHeightGraphFrag();
return wave;
}
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return namme[position];
}
}
Fragments Class
public class TemperatureGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_t, container, false);
return view;
}
}
public class WaveHeightGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_sig_wave_height, container, false);
return view;
}
}
fragment_main XML implemented by FragmentActicity
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#65C2C9"
android:scrollbarSize="5dp"/>
</android.support.v4.view.ViewPager>
Tab 2 Fragment XML graph_sig_wave_height
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/graphWaveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"
android:onClick="changeText"/>
</LinearLayout>
Tab 1 fragment layout XML graph_t
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linearTemp"
>
<TextView
android:id="#+id/graphTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center"
/>
</LinearLayout>
Add the following method to your WaveHeightGraphFrag class:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
final TextView t = (TextView) view.findViewById(R.id.graphWaveTextView);
Button b = (Button) view.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
t.setText("It worked ");
}
});
}
This is what you want.
I develope currently a small sample app with fragments and a viewPager. The viewPager shows 3 pages. In each page i instantiate a fragment of the same type. The fragment contains a textView and a button. On button click I want to replace the current fragment with another one. Now my problem is, no matter which button I press only the fragment of page 1 gets replaced. I dont know what I have to do in my pageAdapter class but I guess it has to do with using the same fragment and layout. I think I have to make sure, that my pageAdapter updates the correct page, but how do I achieve that?
For a better understanding why I want to achieve that, that I receive a json string within 3 node of type menu and I want to use each of them as a page in my viewPager.
Can someone show me a short and easy example for such a behavior? I think its a basic approach, so it cant be so difficult.
--------Edit---------
Here is the code:
public class FragmentPagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 4;
MyAdapter mAdapter;
ViewPager mPager;
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
public MyAdapter getmAdapter() {
return mAdapter;
}
public ViewPager getmPager() {
return mPager;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getFragmentManager(), this);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setOffscreenPageLimit(NUM_ITEMS + 2);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS - 1);
}
});
}
}
MyAdapter:
public MyAdapter(FragmentManager fm, FragmentPagerSupport fragmentPagerSupport) {
super(fm);
this.fragmentPagerSupport = fragmentPagerSupport;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
Fragment newInstance = null;
switch (position) {
case 0:
newInstance = frag1.newInstance(position);
break;
case 1:
newInstance = frag1.newInstance(position);
break;
case 2:
newInstance = frag2.newInstance(position);
break;
case 3:
newInstance = frag2.newInstance(position);
break;
}
return newInstance;
}
Frag1 & Frag2 & ListItemFrag:
public static class frag1 extends ListFragment {
int mNum;
static frag1 newInstance(int num) {
frag1 f = new frag1();
Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class frag2 extends ListFragment {
int mNum;
static frag2 newInstance(int num) {
frag2 f = new frag2();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class ListItemFragment extends Fragment {
String itemName;
static ListItemFragment newInstance(String itemName) {
ListItemFragment i = new ListItemFragment();
Bundle args = new Bundle();
args.putString("text", itemName);
i.setArguments(args);
return i;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemName = getArguments() != null ? getArguments().getString("text") : "NULL";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_item, container, false);
View tv = v.findViewById(R.id.textView1);
((TextView) tv).setText("Cheese: " + itemName + " selected!");
return v;
}
}
Pager Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button
android:id="#+id/goto_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first" />
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="last">
</Button>
</LinearLayout>
Frag1 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
Frag2 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test2">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root2" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
ListItemFrag Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="230dp"
android:background="#AA33EE"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Hi I was facing same kind of issue. I fixed the issue by using
getChildFragmentManager().beginTransaction()
instead of
getActivity().getSupportFragmentManager().beginTransaction()
As in this case we are trying to make transaction from within a fragment (one out of the list of fragments which are attached to the ViewPager, thus the Activity holding the ViewPager) so we have to use getChildFragmentManager() here for desired results.
NOTE: I am using android support v4 library and thus corresponding FragmentManager.