move from ListFragment to Fragment - android

I want to move from my Custom ListView(which is a ListFragment) to another Fragment by onClick() of a Item. I want to also pass some data which I do by
Fragment f = null;
f = new DescriptionFragment();// it extends Fragment
Bundle args = new Bundle();
args.putString("title", "This is title");
args.putString("desc", "This is Description");
f.setArguments(args);
But Nothing happens using this code.
I tried at my level but now I think that I should use FragmentManager & FragmentTransaction. I tried to implement it by writing
FragmentManager fragmentManager;
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(f);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(containerViewId, fragment);// this line gives error & i dont know what to write here
fragmentTransaction.commit();
I think my destination class is fine. It looks like this
public class DescriptionFragment extends Fragment {
public DescriptionFragment(){}
TextView title,desc;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.description,container,false);
Bundle bundle = this.getArguments();
String stitle = bundle.getString("title");
String sdesc = bundle.getString("desc");
TextView title = (TextView)rootView.findViewById(R.id.textView4);
TextView desc = (TextView)rootView.findViewById(R.id.textView3);
title.setText(stitle);
desc.setText(sdesc);
return rootView;
}
}
Does In description.xml do I have to implement FrameLayout??
However description.xml looks like this
<?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"
>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#drawable/flagc">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ashokb" >
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</ScrollView>
</RelativeLayout>
</LinearLayout>
I hope I made my problem clear
Any help?

Create a Frame Layout in your activity.
Create 2 different Fragment Layouts for each fragment.
When a fragment is called use
transaction.replace(frameLayoutId, fragmentToReplace);
transaction.commit()
Here is a sample for a fragment transition that I am using in my App
public void changeTab(View view) {
int id = view.getId();
if (modelSelected) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
InfoFragment info = new InfoFragment();
SettingsFragment settings = new SettingsFragment();
ReportFragment reports = new ReportFragment();
switch (id) {
case R.id.infoTab:
transaction.replace(R.id.loadTabFrag, info);
break;
case R.id.settingsTab:
transaction.replace(R.id.loadTabFrag, settings);
break;
case R.id.reportsTab:
transaction.replace(R.id.loadTabFrag, reports);
break;
default:
break;
}
transaction.commit();
estheticTabHandler(id);
} else {
createSelectModelToast();
}
}
If you want to pass data from one fragment to another you should use a Bundle. In that case you should create a fragment and set its arguments.
Example:
MyFragment myFrag = new MyFragment();
Bundle myBundle = new Bundle();
myBundle.putWhateverData(data); // Where whatever data is the object that you are passing
myFragment.setArguments(myBundle);
And them inside your MyFragment onCreateView() you can use:
Bundle args = this.getArguments();

fragmentTransaction.add(containerViewId, fragment);
in above line where you declare fragment object so it gives error. you remove f fragment but no any valid fragment give so it gives you error.just declare your fragment same as f fragment. thats it...

Related

Replace Fragment results in overlaping fragments

This is a known problem, when I change fragments they overlap.
I followed the examples on the internet with a brand new project to test it out, but no success.
What am I missing here?
I started a simple project with the Navigation Drawer Activity
I've given the fragment_home and fragment_gallery an as id
<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:id="#+id/fragment_home"
android:background="#android:color/background_light"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="333dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I setup fragment manager with the transaction:
public void replaceFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_home, GalleryFragment.class, null);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Created a button and set the method as the onClick activity:
public class HomeFragment extends Fragment {
private View root;
private FragmentHomeBinding binding;
private Button button;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
root = binding.getRoot();
button = root.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Change Fragment
((MainActivity)getActivity()).replaceFragment();
}
});
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
I run the app and press the button, the fragments overlap. What is going on? I've already added a background to the fragments,
did not work. It has something to do with the BackStack, but how? Why is this so difficult? Why can't I simply add and remove a fragment?

Cannot transition to fragment. Function expecting different type

I am trying to create a fragment which will cover half of an activity. I have created the dummy XML, but I cannot transition to it. I have created the fragment through New -> Fragment -> Fragment(Blank). I have not edited the code of the created fragment class, only the XML.
This is my 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="90pt"
android:layout_height="match_parent"
tools:context=".MenuFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Menu"
android:textSize="45dp"
android:paddingLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BLA"
android:textSize="45dp"
android:paddingLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BLA"
android:textSize="45dp"
android:paddingLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BLA"
android:textSize="45dp"
android:paddingLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BLA"
android:textSize="45dp"
android:paddingLeft="10dp"
/>
</LinearLayout>
This is where I want to transition to the fragment. It should be done through a button click.
findViewById(R.id.Menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Menu fragment goes here!", Toast.LENGTH_SHORT).show();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment menuFragment = new MenuFragment();
fragmentTransaction.replace(android.R.id.content, menuFragment);
fragmentTransaction.commit();
}
});
This is the problem:
Wrong 2nd argument type. Found:
'com.example.pogolemotoproektce.MenuFragment', required:
'android.app.Fragment' less...
Inspection info:
replace
(int,
android.app.Fragment)
in FragmentTransaction cannot be applied
to
(int,
com.example.pogolemotoproektce.MenuFragment)
 
occurring on the following line:
fragmentTransaction.replace(android.R.id.content, menuFragment);
You are supposed to use support library, since it's recommended.
Just replace this line :
FragmentManager fragmentManager = getFragmentManager();
With:
FragmentManager fragmentManager = getSupportFragmentManager();
And mind the imports at the top (remove the wrong import, and replace it with proper one, depending whether you use androidx or not, it might differ).
This is how it should be if you're using androidx:
import androidx.fragment.app.FragmentManager;

How to change TextView Value in fragment

I am trying to change TextView value in Fragment but it not clearing old value.
Value is overlapping on old value.
Code from Fragment -
public class MainFragment extends Fragment {
TextView t1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
t1 = view.findViewById(R.id.textview1);
t1.setText(s1);
return view;
}
}
Code from Activity -
public static String s1;
#Override
public void onOptionClicked(int position, Object objectClicked) {
// Set the toolbar title
setTitle(mTitles.get(position));
// Set the right options selected
mMenuAdapter.setViewSelected(position, true);
s1 = mTitles.get(position);
// Navigate to the right fragment
switch (position) {
default:
goToFragment(new MainFragment(), false);
break;
}
// Close the drawer
mViewHolder.mDuoDrawerLayout.closeDrawer();
}
Fragment xml file -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
Tried by using below code but not working....
public void setText(String text){
TextView textView = (TextView) getView().findViewById(R.id.detailsText);
textView.setText(textview1);
}
Please help.... Thanks in Advance...!
If you are using .add in your goToFragment() code, then you should replace with .replace
fragmentTransaction.add(R.id.container,
currentFragment).commit()
to
fragmentTransaction.replace(R.id.fragment_container,
currentFragment).commit()
You can put below code in onCreateView method of your fragment and it will remove this overlapping issue
View view = inflater.inflate(R.layout.your_layout, container, false);
view.setBackgroundColor(Color.WHITE);
fragment.xml add (android:background="#color/white") in your Layout.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
As Ranjan said it is not good practice, why do not you create MainFragment mf = new MainFragment(); inside onCreate() and use that in that method. In this way you will have only one instance. I do not use fragments like this so I do not have good idea about your code otherwise.

Sending bundle from same activity to it's fragment

I'm trying to code my first big project in Android and it's also first time I'm actually writing here. I've been trying to make this issue work for the whole day in vain, and will really appreciate if someone could show me where I'm wrong. I understand that achieving Fragment fields from the activity is bad practice, but it's the only way I don't receive null in my Fragment TextViews. Otherwise the TextViews are null. I've tried to deal with the bundle in different fragment lifecycle events (onAttach and onCreate), but nothing helped, they still don't see the values from the bundle. Thanks a lot in advance!
And one more question, do I understand right that if I want to send a bundle from one activity to other's activity fragment, the only way is to send it to the other activity and then resend to the fragment or make an interface? Maybe there is some straight way I'm not aware about? Thanks a lot in advance!
Here is my FRAGMENT:
public class MatchFragment extends Fragment {
User clickedUser=new User("","","","","",0.0,0.0,0.0,0.0,false,false);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root;
root=inflater.inflate(R.layout.fragment_match,container,false);
Intent intent = getActivity().getIntent();
Bundle bundle = this.getArguments();
if(bundle!=null)
clickedUser = bundle.getParcelable("clickedUser");
else
Toast.makeText(getActivity(),getString(R.string.noMatches),Toast.LENGTH_SHORT).show();
TextView nickNameTv=(TextView)root.findViewById(R.id.matchName);
TextView firstLastNameTv=(TextView)root.findViewById(R.id.firstLastName);
TextView paymentRequiredTv=(TextView)root.findViewById(R.id.paymentRequired);//if payment required - red "payment required", else green "can help for free"
Button mail=(Button)root.findViewById(R.id.mailBtn);
Button call=(Button)root.findViewById(R.id.callBtn);
Button sms=(Button)root.findViewById(R.id.smsBtn);
nickNameTv.setText(clickedUser.nickname);
firstLastNameTv.setText(clickedUser.firstName+" "+clickedUser.lastName);
boolean payment=clickedUser.paymentRequired;
if(payment==true)
{
paymentRequiredTv.setText(getText(R.string.payable));
paymentRequiredTv.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
else
{
paymentRequiredTv.setText(getText(R.string.free));
paymentRequiredTv.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
}
mail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mailIntent = new Intent(Intent.ACTION_SEND);
mailIntent.setType("message/rfc822");
mailIntent.putExtra(Intent.EXTRA_EMAIL, clickedUser.usermail);
mailIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.mailMessage));
// Intent mailer = Intent.createChooser(mailIntent, null);
startActivity(mailIntent);
}
});
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri number = Uri.parse("tel:"+clickedUser.phonenumber);
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
});
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.setData(Uri.parse("sms:"+ clickedUser.phonenumber));
startActivity(smsIntent);
}
});
return root;
}
}
and the XML of it:
<?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="wrap_content"
android:background="#android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="LargeText"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/matchName"
android:layout_marginTop="44dp"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/paymentRequired" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/colorPrimaryDark"
android:text="Large Text"
android:id="#+id/firstLastName"
android:layout_below="#+id/profilePicture"
android:layout_alignEnd="#+id/paymentRequired" />
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/orange_blue_ripple_template"
android:text="#string/call"
android:id="#+id/callBtn"
android:textColor="#android:color/white"
android:layout_alignTop="#+id/smsBtn"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/orange_blue_ripple_template"
android:text="#string/mail"
android:layout_marginStart="36dp"
android:textColor="#android:color/white"
android:id="#+id/mailBtn"
android:layout_alignTop="#+id/callBtn"
android:layout_toEndOf="#+id/callBtn" />
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/orange_blue_ripple_template"
android:textColor="#android:color/white"
android:text="#string/sms"
android:id="#+id/smsBtn"
android:layout_below="#+id/paymentRequired"
android:layout_alignStart="#+id/paymentRequired"
android:layout_marginTop="24dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/profilePicture"
android:layout_below="#+id/matchName"
android:layout_toStartOf="#+id/button2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/paymentRequired"
android:layout_below="#+id/firstLastName"
android:layout_toStartOf="#+id/callBtn" />
</RelativeLayout>
Here is the ACTIVITY:
public class OneMatchActivity extends ToolbarActivity {
User clickedUser=new User("","","","","",0.0,0.0,0.0,0.0,false,false);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_match);
Bundle bundle=getIntent().getExtras();
clickedUser=bundle.getParcelable("clickedUser");
MatchFragment matchFragment = new MatchFragment();// or maybe ?? (MatchFragment)(getSupportFragmentManager().findFragmentById(R.id.fragment));
Bundle bundleToFr = new Bundle();
bundleToFr.putParcelable("clickedUser", clickedUser);
matchFragment.setArguments(bundle);
and the XML of the ACTIVITY:
<?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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/colorPrimary"
tools:context="hyperactive.co.il.helppool.OneMatchActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="hyperactive.co.il.helppool.MatchFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:background="#drawable/helpinghands"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:paddingTop="50dp"
android:paddingBottom="50dp"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
//Activity:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction trans = fm.beginTransaction();
trans.replace(R.id.container, MyFragment.newInstance(arg1, arg2), "tag");
trans.addToBackStack(null).commit();
//Fragment:
public MyFragment() {
// Required empty public constructor
}
public static MyFragment newInstance(String arg1, String arg2)
{
MyFragment frag = new MyFragment();
Bundle args = new Bundle();
args.putString("ARG1", arg1);
args.putString("ARG2", arg2);
frag.setArguments(args);
return frag;
}
#Override public void onViewCreated(View view, Bundle savedInstanceState) {
Bundle args = getArguments();
if(args!=null)
{
String arg1 = args.getString("ARG1");
String arg2 = args.getString("ARG2");
}
}
//Xml
//You can use .add instead .replace method. And in the xml layout you need //to change:
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="hyperactive.co.il.helppool.MatchFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true" /> ,
//to this:
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"/>
MyFragment myF = MyFragment.getInstance(arg1,arg2);
fragmentManager.add(myF);
public class MatchFragment extends Fragment{
public static MatchFragment getInstance(String a, String b){
MyFragment myF = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("a", a);
bundle.putString("b", b);
myF.setArguments(bundle);
return myF
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getArguments();
if (b != null) {
b.getString("a");
b.getString("b");
}
}
}
Instead of passing the parameters in the form of Bundle from Activity to its Fragment, pass the parameters to the the Fragment via a static factory method that instantiates your fragment
MyFragment myF = My fragment.newInstance(arg1,arg2);
fragmentManager.replace(myF);
...

Fragment hide not working in Android

My requirement is, I've a main activity and I want to display an image and text instead of progress bar in a separate fragment.
I've a separate fragment and I want to display the fragment when user clicks on a button in MainActivity.
My issue is, when I start the app, the fragment gets displayed by default. I want the fragment to be displayed only when user clicks on button. When I start the app I want the activity to be displayed.
I've an activity_main xml as below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background" >
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip" >
<TextView
android:id="#+id/text1"
style="#style/textForLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="#string/text1" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dip"
android:layout_weight="1"
android:drawSelectorOnTop="true"
android:prompt="#string/spinner1"
android:spinnerMode="dialog" >
</Spinner>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/text2"
style="#style/textForLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="#string/label2" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dip"
android:layout_span="6"
android:layout_weight="1"
android:drawSelectorOnTop="true"
android:prompt="#string/spinner2"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#color/red"
android:textSize="#dimen/text_medium"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<fragment
android:id="#+id/progress_bar_fragment"
android:name="com.test.pushnotificationeclipse.ProgressBarFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
The fragemnt_progress_bar.xml is as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/NoActionBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_all" >
<ImageView
android:id="#+id/imageView_frag_pgbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/text_frag_pgbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView_frag_pgbar"
android:layout_centerHorizontal="true"
android:layout_marginBottom="74dp"
android:textColor="#color/basic_color"
android:textSize="#dimen/text_medium_large" />
</RelativeLayout>
My ProgressBarFragment.java is as below
public class ProgressBarFragment extends Fragment {
#InjectView(R.id.text_frag_pgbar)
TextView textView;
#InjectView(R.id.imageView_frag_pgbar)
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_progress_bar, container,
false);
ButterKnife.inject(this, view);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onResume() {
super.onResume();
}
}
My MainActivity.java is as below: When I pass true tohideAndShowFragment(), the fragment should be hidden and when I pass false the fragment should be shown.
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
context = getApplicationContext();
hideAndShowFragment(true);
}
public void hideAndShowFragment(boolean hide) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ProgressBarFragment pf = new ProgressBarFragment();
if (hide) {
ft.hide(pf).commit();
} else {
ft.show(pf).commit();
}
}
}
The issue here is your hideAndShowFragment method. You are creating a new instance of ProgressBarFragment, but the FragmentTransaction hide and show methods only work on an attached fragment.
Instead, you should get the fragment you already defined in your XML by id.
public void hideAndShowFragment(boolean hide) {
FragmentManager fm = getFragmentManager();
ProgressBarFragment pf =
(ProgressBarFragment) fm.findFragmentById(R.id.progress_bar_fragment);
FragmentTransaction ft = fm.beginTransaction();
if (hide) {
ft.hide(pf).commit();
} else {
ft.show(pf).commit();
}
}
Additionally, this line is concerning:
context = getApplicationContext();
Your Activity is also a Context object, so unless you need the application specific context for something, you generally want to be using this where you need a context inside your activity.
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(yourfragment)
.commit();
Ps:-Dont Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.
Src:- "https://stackoverflow.com/a/16490344/1632286"
You might be better of getting an instance of the fragment in code and using the technique from the official docs as shown below and here (search for 'newInstance'). Add the following static method to your fragment.
public static ProgressFragment newInstance() {
DetailsFragment f = new DetailsFragment();
// Supply args here if needed.
/*Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);*/
return f;
}
Once you have that you can add the fragment to the top view layout with the following fragment transaction code which is inside the button click method.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction tr = fm.beginTransaction();
tr.add(android.R.id.content, ProgressFragment.newInstance(), "ProgressFragmentTag");
tr.commit();
You can then use the following code to remove the fragment if needed;
FragmentManager fm = getSupportFragmentManager();
ProgressFragment frag = fm.findFragmentByTag("ProgressFragmentTag")
if (frag!=null)
{
FragmentTransaction tr = fm.beginTransaction();
tr.remove(frag).commit();
}
Hope this helps!
I resolved it by adding the fragment instead of having it shown:
public void hideAndShowFragment(boolean hide) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ProgressBarFragment pf = (ProgressBarFragment) fm.findFragmentById(R.id.progress_bar_fragment);
if (hide) {
ft.hide(pf).commit();
} else {
ft.add(android.R.id.content, pf, "ProgressFragmentTag").commit();
}
}
int count =1;
if (count == 1) {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction =
fm.beginTransaction();
fragmentTransaction.replace(R.id.labelframe, new
labelfregaments());
fragmentTransaction.commit();
count =0;
}
else if (count == 0) {
FragmentManager fm = getFragmentManager();
labelfregaments fs = (labelfregaments)fm.findFragmentById(R.id.labelframe);
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.hide(fs);
fragmentTransaction.commit();
count=1;
}

Categories

Resources