I know there are a bunch of answers on StackOverflow regard my question but none of them fixed my problem as my Fragments are static.
I have two fragments in my activity. The second one is covering the first one and this is the fragment that will be shown/hidden.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FeedActivity">
<fragment
android:id="#+id/listViewFragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:name="com.me.cscomponents.fragFeed.FeedFragment"
tools:layout="#layout/fragment_feed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/gh1"
app:layout_constraintBottom_toBottomOf="parent"/>
<fragment
android:id="#+id/playerViewFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.me.cscomponents.fragPlayer.PlayerFragment"
tools:layout="#layout/fragment_player"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/gh1"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
In the TV app, both of Fragments are visible side by side. However, in the mobile app, listViewFragment is visible by default and playerViewFragment displays when an item in listViewFragment clicks by the user. When the user clicks on the Back button then this view becomes hidden (and therefore listViewFragment becomes visible).
This is my code (but it doesn't work as I expect):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feed)
listFragment = supportFragmentManager.findFragmentById(R.id.listViewFragment) as FeedFragment
playerFragment = supportFragmentManager.findFragmentById(R.id.playerViewFragment) as PlayerFragment
val d1: Disposable = listFragment.onClickSubject
.subscribe {
showOrHidePlayerFragment(true)
playerFragment.streamCamera(it.camFeedUrl)
}
cd.add(d1)
showOrHidePlayerFragment(false)
}
private fun showOrHidePlayerFragment(isVisible: Boolean) {
val fm = supportFragmentManager.beginTransaction()
if (isVisible) fm.show(playerFragment) else fm.hide(playerFragment)
fm.commit()
}
The problem is playerFragment is still visible when I launch the activity. So, I have no idea how to fix the issue and what is the cause of the problem.
My current workaround is to surround my playerFragment in a FrameLayout and make this view visible/invisible. This approach works fine.
I think few stuff went wrong with your coding. Try to avoid hard coding fragment like
android:name="com.me.cscomponents.fragFeed.FeedFragment"
Based on your question i prepared a something for you. I just implemented two button click rather publishing a list. Passed an int (you can pass according to your need.). I tried to follow few best practices. For simplicity i used LinearLayout & RelativeLayout.
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
TestActivity.java
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class TestActivity extends AppCompatActivity implements FeedFragment.OnItemClickedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, FeedFragment.getInstance(), FeedFragment.TAG).commit();
}
#Override
public void onButtonClicked(int position) {
getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragment_container, PlayerFragment.getInstance(position), PlayerFragment.TAG).commit();
}
#Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof FeedFragment) {
FeedFragment feedFragment = (FeedFragment) fragment;
feedFragment.setOnButtonClickedListener(this);
}
}
}
fragment_feed.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Feed 1" />
<Button
android:id="#+id/button_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Feed 2"/>
</LinearLayout>
FeedFragment.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FeedFragment extends Fragment {
public static final String TAG = FeedFragment.class.getSimpleName();
View view;
OnItemClickedListener callback;
Button buttonOne;
Button buttonTwo;
public static FeedFragment getInstance(){
FeedFragment fragment = new FeedFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.feed_fragment, container, false);
buttonOne = view.findViewById(R.id.button_one);
buttonTwo = view.findViewById(R.id.button_two);
init();
return view;
}
private void init() {
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onButtonClicked(1);
}
});
buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onButtonClicked(2);
}
});
}
public void setOnButtonClickedListener(OnItemClickedListener callback) {
this.callback = callback;
}
public interface OnItemClickedListener {
public void onButtonClicked(int position);
}
}
fragment_player.xml
<?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">
<TextView
android:id="#+id/demo_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
PlayerFragment.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class PlayerFragment extends Fragment {
public static final String TAG = PlayerFragment.class.getSimpleName();
private static final String ARG_POSITION = "position";
private View view;
private TextView demoTextView;
private int position;
public static PlayerFragment getInstance(int position){
PlayerFragment fragment = new PlayerFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null ){
position = getArguments().getInt(ARG_POSITION);
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_player, container, false);
demoTextView = view.findViewById(R.id.demo_text_view);
init();
return view;
}
private void init() {
demoTextView.setText("Player Fragment, clicked position "+ position);
}
}
Hope it will help you. Thanks.
The tag fragment has an id, the Fragment root view will have that id.
So it will be
findViewById(R.id.oneFragment).setVisibility(View.GONE);
By example, if FragmentOne use the following layout:
<LinearLayout>
<!--Chile Viiews-->
</LinearLayout>
And you are using the tag fragment, like this:
<fragment
id=oneFragment
name=FragmentOne/>
Then that linear layout will end up having oneFragment as id. That is how the tag fragment works after the fragment is attached the tag fragment id is assigned to the root view o the fragment. You can read more here.
Another way to do this is to use the fragment manager, here is a one-liner:
getSupportFragmentManager().findFragmentById(R.id.fragment).getView().setVisibility(View.GONE);
Related
i am using the new android viewpager2, but when i load different fragments, the viewpager2 shows only the same fragments..
Is this an error? in the older viewpager everything worked.
As you can see here in the images, the android app load the same fragments.
In the viewPagerAdapter I load or create for each position a different fragment
Code ViewPagerAdaptor
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity)
{
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new page1();
case 1:
return new page2();
default:
return new pageDefault();
}
}
#Override
public int getItemCount() {return 3; }
}
The MainActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tabs);
viewPager2 = findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager2,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
}
here come the fragments
fragment_page1
<?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/fragment_page1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".page1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textSize="20sp"
android:textStyle="bold"
android:text="This is Page 0" />
</FrameLayout>
and fragment_page2
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".page2">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"
android:text="This is Page 02"
android:background="#color/red_100"/>
</FrameLayout>
and the java code of page1.java
package com.example.demo_viewpager2;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class page1 extends Fragment {
public page1() {
// Required empty public constructor
}
public static page1 newInstance() {
page1 fragment = new page1();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_page1, container, false);
}
}
After trying the code provided and add the missing files, i am unable to replicate your issue and is working fine on my testing.
ViewPagerAdapter.java file
package com.example.adapter;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.example.fragment.page1;
import com.example.fragment.page2;
import com.example.fragment.pageDefault;
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new page1();
case 1:
return new page2();
default:
return new pageDefault();
}
}
#Override
public int getItemCount() {
return 3;
}
}
MainActivity.java file
package com.example.view;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.example.R;
import com.example.adapter.ViewPagerAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = findViewById(R.id.tabs);
ViewPager2 viewPager2 = findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager2,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
}
}
page1.java file
public class page1 extends Fragment {
public page1() {
// Required empty public constructor
}
public static page1 newInstance() {
page1 fragment = new page1();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_page1, container, false);
}
}
page2.java file
public class page2 extends Fragment {
public page2() {
// Required empty public constructor
}
public static page2 newInstance() {
page2 fragment = new page2();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page2, container, false);
}
}
pageDefault.java file
public class pageDefault extends Fragment {
public pageDefault() {
// Required empty public constructor
}
public static pageDefault newInstance() {
pageDefault fragment = new pageDefault();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page_default, container, false);
}
}
main_activity.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
fragment_page1.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_page1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="This is Page 0"
android:textSize="20sp"
android:textStyle="bold" />
</FrameLayout>
fragment_page2.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"
android:text="This is Page 02"
android:background="#android:color/holo_red_light"/>
</FrameLayout>
fragment_page_default.xml file
<?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:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"
android:text="This is Page Default"/>
</FrameLayout>
Output:
thank you, this workes really fine.
there was an typo error in the inflate of page2 to the page1
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page1, container, false);
}
I'm trying to make an app (for learning purposes) where I have a few tabs with scrollable content.
I have a collapsing app bar with a ViewPager for the main layout and three identical layouts with a TextView inside a NestedScrollView where the only difference is the image on top of the text. I also have three fragment classes with the same code inside. Everything worked fine.
But since I'm using the same layout in each tab, I thought that instead of a xml file and a java class for each tab, I could just have one of each and then somehow change the content for each tab inside my Adapter.
So I tried to just create a method to do that inside my tabFragment class. But I can't seem to find a way to modify the TextView. I keep getting a NullPointerException every time.
What am I missing?
Is my approach wrong? If so, what would be a better one? How do I solve this?
Thank you in advance :)
Here's my fragment class right now (the only one remaining ):
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.example.tablayoutwithscrollview.R;
public class TabFragment extends Fragment {
private TextView textView;
private int text, image;
public TabFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tab1, container, false);
//textView = view.findViewById(R.id.textView);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
textView = getView().findViewById(R.id.textView);
}
public void setTabContent(int text, int image)
{
textView.setText(text);
textView.setCompoundDrawablesWithIntrinsicBounds(0,image,0,0);
}
}
My adapter class:
import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.tablayoutwithscrollview.Tabs.TabFragment;
public class MyAdapter extends FragmentPagerAdapter {
private static int tabCount;
Context context;
public MyAdapter(FragmentManager fm, int tabCount, Context context){
super(fm);
this.tabCount = tabCount;
this.context = context;
}
#Override
public Fragment getItem(int position) {
TabFragment fragment;
switch (position)
{
case 0:
fragment = new TabFragment();
fragment.setTabContent(R.string.lorem_ipsum, R.drawable.jackfruit);
return fragment;
case 1:
fragment = new TabFragment();
fragment.setTabContent(R.string.lorem_ipsum, R.drawable.guava);
return fragment;
case 2:
fragment = new TabFragment();
fragment.setTabContent(R.string.lorem_ipsum, R.drawable.pomegranate);
return fragment;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position)
{
switch (position)
{
case 0:
return context.getString(R.string.tab1_title);
case 1:
return context.getString(R.string.tab2_title);
case 2:
return context.getString(R.string.tab3_title);
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
MainActivity:
package com.example.tablayoutwithscrollview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
populatesTabLayout(tabLayout);
MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), this);
viewPager.setAdapter(myAdapter);
tabLayout.setupWithViewPager(viewPager);
}
private void populatesTabLayout(TabLayout tabLayout)
{
for (int i = 0; i<3; i++)
{
tabLayout.addTab(tabLayout.newTab());
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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/coordLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapseToolBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/strawberry" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"></androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:visibility="visible" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
And my tab layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tabNestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableTop="#drawable/jackfruit"
android:text="#string/lorem_ipsum" />
</androidx.core.widget.NestedScrollView>
Here's how it's supposed to work (from before when each tab had a fragment class and a layout file):
The problem is that the created TabFragment instance has not been attached to the activity yet, therefore the textView does not inflated at that point.
You should pass the text to the TabFragment instance as an argument in the MyAdapter#getItem(..) method.
...
case 0:
fragment = new TabFragment();
Bundle args = new Bundle();
args.putString("key", textString);
fragment.setArguments(args);
return fragment
...
After that set the text for the TextView instance in the onViewCreated(...) method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = getView().findViewById(R.id.textView);
textView.setText(getArguments().getString("key"));
}
Or you can see a nice example at the Android Reference.
I have fragment activity that have view pager, I want every changing page the content is change programmatically. `
package com.idroid.splashscreen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class ScreenSlidePagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
OnPageChangeListener pageChangeListener=null;
pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext()
.getApplicationContext(),
"page "+position,
Toast.LENGTH_LONG).show();
TextView txt=(TextView) findViewById(R.id.txtcoba);
txt.setText("page "+position);
}
};
mPager.setOnPageChangeListener(pageChangeListener);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
`
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtcoba"
style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="coba" />
</ScrollView>
I change it on page selected method and change the content of text view. for the toast it's work but for the text doesn't change. but on page 4 when I back to page 3, the page 3 show the page. but the other page not.
what should I do ? thanks before. this is the ScreenSlidePageFragment class
package com.idroid.splashscreen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
this is fragment_screen_slide_page.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtcoba"
style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="coba" />
</ScrollView>
this is activity_screen_slide.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Issue is your trying to set the TextView of Fragment layout.
As per your code your TextView is in the ScreenSlidePageFragment layout.
Remove the 'TextView' setText in onPageeSelcted
Change your ScreenSlidePageFragment like this
private class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View row = inflater.inflate(R.layout.activity_screen_slide, container, false);
TextView txt=(TextView) row.findViewById(R.id.txtcoba);
txt.setText("page using fragment");
return row;
}
}
I am very new to android programming and I am trying to implement tabs using fragments.
I am using this Tutorial. Everything goes fine but my problem is that I want to open a new activity and on this new activity I want to keep tab bar. I want tab bar visible on every new activity which opens inside tab. I have following code..
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout theLayout = (LinearLayout) inflater.inflate(
R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button) theLayout.findViewById(R.id.btn_startActivity);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(),
"open new activity with tab bar", Toast.LENGTH_LONG).show();
//Here I want to start new activity with tab bar
}
});
return theLayout;
// return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout,
// container, false);
}
}
Here is Main Activity.
package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.sample.fragments.R;
public class FragmentTabs extends SherlockFragmentActivity implements FragmentChangeListener
{
private TabHost mTabHost;
private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private View tabIndicator1;
private View tabIndicator2;
private View tabIndicator3;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mContainerId=R.id.realtabcontent;
fragmentManager = getSupportFragmentManager();
tabIndicator1 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
tabIndicator2 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
tabIndicator3 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
TextView tv1=(TextView)tabIndicator1.findViewById(R.id.txt);
TextView tv2=(TextView)tabIndicator2.findViewById(R.id.txt);
TextView tv3=(TextView)tabIndicator3.findViewById(R.id.txt);
tv1.setText("Tab1");
tv2.setText("Tab2");
tv3.setText("Tab3");
mTabHost.addTab(mTabHost.newTabSpec("1")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator1)
);
mTabHost.addTab(mTabHost.newTabSpec("2")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator2)
);
mTabHost.addTab(mTabHost.newTabSpec("3")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator3)
);
mTabHost.setOnTabChangedListener(new OnTabChangeListener()
{
#Override
public void onTabChanged(String selectedTabID)
{
int tabIndex=Integer.valueOf(selectedTabID);
switch(tabIndex)
{
case 1:
selectedTabID= tabIndicator1.getTag()==null?"Fragment1":tabIndicator1.getTag().toString();
break;
case 2:
selectedTabID= tabIndicator2.getTag()==null?"Fragment2":tabIndicator2.getTag().toString();
break;
case 3:
selectedTabID= tabIndicator3.getTag()==null?"Fragment3":tabIndicator3.getTag().toString();
break;
};
Fragment fragment=fragmentManager.findFragmentByTag(selectedTabID);
if(fragment==null)
{
fragment=getFragment(selectedTabID);
}
replaceFragment(fragment,selectedTabID);
}
});
renderDefaultTab();
}
public void clickMe(final View view)
{
Fragment fragment=new AnotherFragment();
replaceFragment(fragment,"AnotherFragment");
}
#Override
public void replaceFragment(final Fragment fragment, final String tag)
{
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment,tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
public void renderDefaultTab()
{
Fragment fragment=getFragment("Fragment1");
replaceFragment(fragment,"Fragment1");
}
public Fragment getFragment(final String tag)
{
Fragment fragment=null;
if(tag.equalsIgnoreCase("Fragment1"))
fragment=new Fragment1();
else if(tag.equalsIgnoreCase("Fragment2"))
fragment=new Fragment2();
else if(tag.equalsIgnoreCase("Fragment3"))
fragment=new Fragment3();
return fragment;
}
#Override
public void addToTab1Navigation(final String tag)
{
tabIndicator1.setTag(tag);
}
#Override
public void addToTab2Navigation(final String tag)
{
tabIndicator2.setTag(tag);
}
#Override
public void addToTab3Navigation(final String tag)
{
tabIndicator3.setTag(tag);
}
#Override
public void onBackPressed()
{
String name=fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1).getName();
Fragment fragment=fragmentManager.findFragmentByTag(name);
if(fragment instanceof BaseFragment){
String tag=((BaseFragment)fragment).getPreceddingFragmentTag();
if(tag.equalsIgnoreCase("exit"))
System.exit(0);
else
{
fragment=fragmentManager.findFragmentByTag(tag);
replaceFragment(fragment, tag);
}
}
}
}
and layout of this MainActivity.
<?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+android:id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_gravity="bottom"/>
</LinearLayout>
</TabHost>
Fragment1:
package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment1 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment1";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment1, container, false);
return view;
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
CustomAdapter adapt=new CustomAdapter(getActivity(),0);
ListView lv=(ListView)view.findViewById(R.id.mylistview);
lv.setAdapter(adapt);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(final AdapterView<?> arg0, final View arg1, final int position, final long arg3)
{
Fragment fr=new CustomFragment();
Bundle bundle=new Bundle();
bundle.putString("response", "Option "+(position+1));
fr.setArguments(bundle);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr,"CustomFragment");
}
});
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
Fragment2:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment2 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment2";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment2, container, false);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab2Navigation(this.toString());
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
Fragment3:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment3 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment3";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment3, container, false);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab3Navigation(this.toString());
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
FragmentChangeListener Interface.
package com.example.tabs;
import android.support.v4.app.Fragment;
public interface FragmentChangeListener
{
public void replaceFragment(final Fragment fragment, final String tag);
public void addToTab1Navigation(String tag);
public void addToTab2Navigation(String tag);
public void addToTab3Navigation(String tag);
}
DummyTabFactory:
package com.example.tabs;
import android.content.Context;
import android.view.View;
import android.widget.TabHost;
class DummyTabFactory implements TabHost.TabContentFactory
{
private final Context mContext;
public DummyTabFactory(final Context context)
{
mContext = context;
}
#Override
public View createTabContent(final String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
CustomFragemnt:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.sample.fragments.R;
public class CustomFragment extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "CustomFragment";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
View view=inflater.inflate(R.layout.custom_fragment, container, false);
TextView tv=(TextView)view.findViewById(R.id.response);
tv.setText("You Clicked "+getArguments().getString("response"));
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "Fragment1";
}
}
CustomAdapter:
package com.example.tabs;
import com.actionbarsherlock.sample.fragments.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.Activity;
public class CustomAdapter extends ArrayAdapter<String>
{
Context mcontext;
public CustomAdapter(final Context context, final int textViewResourceId)
{
super(context, textViewResourceId);
mcontext=context;
}
#Override
public int getCount()
{
return 50;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent)
{
View row;
if(convertView==null)
{
LayoutInflater inflater = ((Activity)mcontext).getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
}
else
{
row=convertView;
}
TextView tv=(TextView)row.findViewById(R.id.textView1);
tv.setText("Option "+(position+1));
return row;
}
}
BaseFragment:
package com.example.tabs;
import com.actionbarsherlock.app.SherlockFragment;
public abstract class BaseFragment extends SherlockFragment
{
public abstract String getPreceddingFragmentTag();
}
AnotherFragment:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class AnotherFragment extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
View view=inflater.inflate(R.layout.another_fragment, container, false);
return view;
}
#Override
public String toString()
{
return "AnotherFragment";
}
#Override
public String getPreceddingFragmentTag()
{
return "CustomFragment";
}
}
Layout for AnotherFragment.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/another"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Layout for CustomFragment:
*<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/response"
android:text="#string/another_fragment"
android:onClick="clickMe" />
</RelativeLayout>*
Layout for Frament1:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/mylistview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Layout for Fragment2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/some_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Layout for Fragment3:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/icon"
android:contentDescription="#string/desc" />
</RelativeLayout>
Layout for Row.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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:padding="5dp" />
</RelativeLayout>
Tab.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity"
android:layout_margin="3dp"
android:background="#drawable/two_state_button"
android:layout_weight="1">
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_compose_inverse"
android:layout_centerHorizontal="true"
android:contentDescription="#string/desc"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/img"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android"></menu>
My suggestion is you should you fragments instead on using new activity. Fragment will be displayed withing your current activity and you don't need to take care about tabs.
but if your need is to use Activity then Create tabhost in newActivity layout as well as you made in this Activity's Layout.
and while creating intent of another activity, send the current Tab number in extras to new Activity.
Intent i = new Intent(Activity.this, NewActivity.Class);
i.putIntExtra("CurrentVisibleTab", currentTabIndex);
startActivity(i).
In New Activity.
tabHost.setDefault(getIntent().getIntExtra("CurrentVisibleTab"));
Hope this will helpful.
I create a fragment extend class to call layout as following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/date_time_label"
android:layout_centerVertical="true"
android:layout_marginLeft="200dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32dp"
android:textStyle="bold"
android:text="time_label"
/>
<TextView
android:id="#+id/last_view_time"
android:layout_toRightOf="#+id/date_time_label"
android:layout_alignBaseline="#+id/date_time_label"
android:layout_marginLeft="8dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="32dp"
/>
</LinearLayout>
package com.appnetics;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* DateTime
*/
public class details extends Fragment {
private static String getDateTimeString(Date time) {
return new SimpleDateFormat("d MMM yyyy HH:mm:ss")
.format(time);
}
private final String time = getDateTimeString(new Date());
/** #see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) */
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle b)
{
View view = inflater.inflate(
R.layout.details,
container,
false); //!!! this is important
((TextView) view.findViewById(R.id.last_view_time))
.setText(time);
return view;
}
}
now to use it I create layout like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_showdetails"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginLeft="110dip"
android:layout_marginTop="15dip"
android:text="Show Details" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/my_parent_layout"
>
</LinearLayout>
</LinearLayout>
on the click event of the button I say
setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
details fragment = new details();
fragmentTransaction.add(R.id.my_parent_layout, fragment);
fragmentTransaction.commit();
}
});
but it raise error
The method getFragmentManager() is undefined for the type new View.OnClickListener(){}
any idea how to solve that
if call activity from fragment then code below or call fragment to fragment then simply replace the code instead of startactivity onclick method
public class FragmentA extends Fragment implements OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
Button button1 = (Button) v.findViewById(R.id.StartButton);
button1.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),testing.class));
}
}
}
Declare and set the fragmentManager as final, before the listener definition.
final FragmentManager fragmentManager = getFragmentManager();
<your listener declaration>
you should be able to use it in the listener.
Below code works
Button publishButton =(Button)
fragmentView.findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
publish();
}
});