call fragment issue in button onclick - android

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();
}
});

Related

Changing a fragment on a button click within a fragment

Iam trying to change a fragment when a button is clicked on that fragment. While doing so the fragment changes but the button still appears on the changed fragment. Iam new to developing , someone please help me bug this issue.
HomeFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.vinodsharma.hcms_attendance_app.R;
import com.vinodsharma.hcms_attendance_app.databinding.FragmentHomeBinding;
import com.vinodsharma.hcms_attendance_app.fragments.NewFragment;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
FragmentHomeBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// homeViewModel =
// ViewModelProviders.of(this).get(HomeViewModel.class);
// View root = inflater.inflate(R.layout.fragment_home, container, false);
// final TextView textView = root.findViewById(R.id.text_home);
// homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
// #Override
// public void onChanged(#Nullable String s) {
// textView.setText(s);
// }
// });
// return root;
binding=FragmentHomeBinding.inflate(getLayoutInflater());
return binding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.btnAttendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment NewFragment=new NewFragment();
FragmentManager manager=getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction= manager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment,NewFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
//*****To avoid memory leaks****8
#Override
public void onDestroyView() {
super.onDestroyView();
binding=null;
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ui.home.HomeFragment">
<Button
android:id="#+id/btn_goto_new"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#00f"
android:gravity="center"
android:textColor="#ffff"
android:textSize="20sp"
android:text="Go To New Fragment"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
NewFragment.java
public class NewFragment extends Fragment {
public NewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_new, container, false);
}
}
fragment_new.xml
<?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=".fragments.NewFragment"
>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment"
android:layout_gravity="center"
android:textColor="#ffff"
android:textSize="24sp"/>
</FrameLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
You using navHostFragment. Documentation:
https://developer.android.com/guide/navigation/navigation-getting-started
You should create in nav graph action, and do something like that:
public void onClick(View v) {
findNavController().navigate(R.id.action...)
}

How to show/hide a static fragment in Android

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);

Refresh Fragment View inside itself

I have a big request for any of You. I would like to create a third Fragment in my simple application. Everything works fine, no error. I would like to make the last Fragment it is: "TestFragment" when I click that button inside that Fragment I'd like to refresh its View (on click button) and load another view inside this fragment (the same fragment). Please help me do this, show how to get it. I have read in Google but can not find the solution appropriate for this application.
Here is simple code:
MAIN ACTIVITY:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TestFragment();
// case 1:
// return new ImageFragment();
case 1:
return new TestFragment();
//
default:
return null;
}
}
}
}
TEST FRAGMENT:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
// TextView textView = (TextView) view.findViewById(R.id.detailsText);
// textView.setText("Testing");
return view;
}
}
TEST LAYOUT:
<?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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QUIZ IMPORTANT TAKE A LOOK AT THIS!!!!!"
android:textSize="30dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_marginLeft="30dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asdjiasdjasoldjasjdasjdlasjdksahfkadshfalidshfladshfladsfhlasdfgjl;adkglkafdgnklfdsgjpfasmga.dsnvlkasdnvkldsnflkdasjflkasdnvlkadjvodsijfosdjv;lasdvlasdjvladosijao" />
DETAILS FRAGMENT:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Details extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details, container, false);
TextView textView = (TextView) view.findViewById(R.id.detailsText);
textView.setText("Testing");
return view;
}
}
ACTIVITY_MAIN LAYOUT:
<?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="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
DETAILS LYOUT:
<?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="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
How to do this refresh inside the same fragment?

Fragment with ViewPager inside Fragment and FragmentStatePagerAdapter results in Exception (with complete example)

I have a simple Fragment with a ViewPager.
I'm using the up to date support library, v4 rev18!
If I show the sub fragment the first time, everything works fine, if I go back and show it again, the app crashes with the following exception:
I have a complete example which shows, WHEN the following exception is occuring:
java.lang.NullPointerException
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:569)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1281)
at android.view.View.dispatchRestoreInstanceState(View.java:12043)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2688)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2694)
at android.view.View.restoreHierarchyState(View.java:12021)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:425)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:949)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4800)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
at dalvik.system.NativeStart.main(Native Method)
I am able to use the ViewPager in a child fragment in every other way, but I can't get it working if I add/remove the sub fragments manually and use a FragmentStatePagerAdapter in the sub fragments...
Following example should work, but it doesn't... i already added some code which solves some problems, but it does not solve all problems...
import java.lang.reflect.Field;
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.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestActivity extends FragmentActivity implements OnClickListener
{
private Fragment fragment1;
private Fragment fragment2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_main);
fragment1 = getSupportFragmentManager().findFragmentByTag("fragment1");
fragment2 = getSupportFragmentManager().findFragmentByTag("fragment2");
}
#Override
public void onClick(View v)
{
Fragment nextFragment = null;
String nextFragmentTag = null;
if (v.getId() == R.id.button1)
{
if (fragment1 == null)
fragment1 = ContainerFragment.newInstance(1);
nextFragment = fragment1;
nextFragmentTag = "fragment1";
}
else if (v.getId() == R.id.button2)
{
if (fragment2 == null)
fragment2 = ContainerFragment.newInstance(2);
nextFragment = fragment2;
nextFragmentTag = "fragment2";
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main, nextFragment, nextFragmentTag);
transaction.addToBackStack(null);
transaction.commit();
}
public static class MainPagerAdapter extends FragmentStatePagerAdapter
{
public int button;
public MainPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
return SubFragment.newInstance(button, i);
}
#Override
public int getCount()
{
return 10;
}
}
public static class ContainerFragment extends Fragment
{
static ContainerFragment newInstance(int pos)
{
ContainerFragment f = new ContainerFragment();
Bundle args = new Bundle();
args.putInt("pos", pos);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.view_pager, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
MainPagerAdapter adapter = new MainPagerAdapter(getChildFragmentManager());
adapter.button = getArguments().getInt("pos");
pager.setAdapter(adapter);
return rootView;
}
// ---------------------------------------------------------------
// HACK FIX für java.lang.IllegalStateException: No activity
// ---------------------------------------------------------------
private static final Field sChildFragmentManagerField;
static
{
Field f = null;
try
{
f = android.support.v4.app.Fragment.class.getDeclaredField("mChildFragmentManager");
f.setAccessible(true);
}
catch (NoSuchFieldException e)
{
}
sChildFragmentManagerField = f;
}
#Override
public void onDetach()
{
super.onDetach();
if (sChildFragmentManagerField != null)
{
try
{
sChildFragmentManagerField.set(this, null);
}
catch (Exception e)
{
}
}
}
}
public static class SubFragment extends Fragment
{
static SubFragment newInstance(int button, int pos)
{
SubFragment f = new SubFragment();
Bundle args = new Bundle();
args.putString("key", "Button " + button + "Fragment " + pos);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.test_subfragment, container, false);
((TextView) rootView.findViewById(R.id.tv1)).setText(getArguments().getString("key"));
return rootView;
}
}
}
for the sake of completeness, I add the xml files as well:
test_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Button2" />
</LinearLayout>
</FrameLayout>
test_subfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="50sp" />
view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/llContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Add an additional FrameLayout to your layout of the main activity. This is where you put the Fragment.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Button2" />
<!-- add this -->
<FrameLayout
android:id="#+id/fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
</FrameLayout>
Since you are adding your Fragments to the BackStack, there is no need for saving an instance of them. This is the reason why you app crashes. Adjust your onClick() method as follows:
#Override
public void onClick(View v)
{
Fragment nextFragment = null;
String nextFragmentTag = null;
if (v.getId() == R.id.button1)
{
nextFragment = ContainerFragment.newInstance(1);
nextFragmentTag = "fragment1";
}
else if (v.getId() == R.id.button2)
{
nextFragment = ContainerFragment.newInstance(2);
nextFragmentTag = "fragment2";
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_frame, nextFragment, nextFragmentTag);
transaction.addToBackStack(null);
transaction.commit();
}
I tested the code. Changing the Fragments with the buttons works, and
the state the ViewPager was left when returing to it is preserved.

how to keep tabs visible on every activity

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.

Categories

Resources