I want to click the button to go from fragment to activity. But it is not working
this is fragment class
package com.hmat.foodrider;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class StatusFragment extends Fragment {
// go is start , request break button//
public StatusFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = null;
v= inflater.inflate(R.layout.fragment_status, container, false);
Button go= (Button)v.findViewById(R.id.button);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), StartActivity.class);
startActivity(intent);
}
});
return v;
}
}
That activity is working fine but I can not go from fragment to that activity using the button.
And this is the screenshot
enter image description here
You can write :
v.getContext().startActivity(intent);
Instead of :
startActivity(intent);
Related
I'm trying to remove a fragment and it's not working.
I've been checking with logcat and it's noticing that the button's been clicked and that message is being passed to the main activity. I assume there's something wrong with my code but I can't figure out what that is. Would appreciate some help.
MainMenu.java
package com.example.android.learninstrumentation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainMenu extends AppCompatActivity implements MainMenuStFrag.MainMenuStFragListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
//Create a new Fragment to be placed in the Activity layout
Fragment menuSiFragment = new MainMenuSiFrag();
Fragment menuStFragment = new MainMenuStFrag();
//Add the fragment to the 'fragment_container' layout
getSupportFragmentManager().beginTransaction().add(R.id.fragment_type_si_container, menuSiFragment).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_type_st_container, menuStFragment).commit();
}
//The user clicked 'expand' from MainMenuStFrag. Remove MainMenuSiFrag.
public void onExpandClick () {
Log.i("MainMenu", "Click message received");
Fragment oldFragment = new MainMenuSiFrag();
getSupportFragmentManager().beginTransaction().remove(oldFragment).addToBackStack(null).commit();
}
public void onCheckboxClick() {
}
}
MainMenuStFrag.java
package com.example.android.learninstrumentation;
import android.app.Activity;
import android.content.Context;
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.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
public class MainMenuStFrag extends Fragment implements View.OnClickListener{
MainMenuStFragListener mCallback;
//Inflate the layout and set buttons for this fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Store the Fragment in the mainMenu variable
View mainMenu = inflater.inflate(R.layout.main_menu_st_fragment, container, false);
//Define the buttons and set onClickListeners
ImageView expand = mainMenu.findViewById(R.id.mainMenu_imageView_SelectTopics);
expand.setOnClickListener(this);
CheckBox checkBox = mainMenu.findViewById(R.id.mainMenu_CheckBox_SelectAllTopics);
checkBox.setOnClickListener(this);
return mainMenu;
}
//Interface for communication with container Activity
public interface MainMenuStFragListener {
void onExpandClick();
void onCheckboxClick();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
//This makes sure the container Activity has implemented the callback interface.
// If not, it throws an exception.
try {
mCallback = (MainMenuStFragListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
//onClick actions
#Override public void onClick(View v) {
switch (v.getId()) {
//Remove the other 'type' item
case R.id.mainMenu_imageView_SelectTopics:
Log.i("MainMenuStFrag", "Topics>Expand=Clicked");
mCallback.onExpandClick();
break;
case R.id.mainMenu_CheckBox_SelectAllTopics:
mCallback.onCheckboxClick();
break;
}
}
}
MainMenuSiFrag.java
package com.example.android.learninstrumentation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainMenuSiFrag extends Fragment {
//Inflate the layout for this fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainMenu = inflater.inflate(R.layout.main_menu_si_fragment, container, false);
return mainMenu;
}
}
You have created new instance of Fragment for remove Fragment
public void onExpandClick () {
Log.i("MainMenu", "Click message received");
Fragment oldFragment = new MainMenuSiFrag();
getSupportFragmentManager().beginTransaction().remove(oldFragment).addToBackStack(null).commit();
}
instead on that Find a fragment and remove it from container
Fragment oldFragment=getSupportFragmentManager().findFragmentById(R.id.fragment_type_si_container);
if(oldFragment!=null && oldFragment instanceof MainMenuSiFrag)
{
getSupportFragmentManager()
.beginTransaction().
remove(oldFragment).commit();
}
I can run this code , but when i click button on my checkbalance layout , my app closed ,can someone help me pls, my checkbalance actually is a fragment from my navigation drawer activity,my idea is when i click the button on check balance,it will go to makepayment page
Checkbalance.java
package com.helloworld.basikal;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by LENOVO on 8/21/2017.
*/
public class CheckBalance extends Fragment{
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Check Balance");
Button button = (Button) getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MadePayment.class);
getActivity().startActivity(intent);
}
});
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.checkbalance,container,false);
}
}
Madepayment.java
package com.helloworld.basikal;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by LENOVO on 8/24/2017.
*/
public class MadePayment extends Fragment{
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.madepayment, container, false);
Intent intent = getActivity().getIntent();
return view;
}
}
It seems that class MadePayment is a fragment. But you treated it as a activity.
// error code start here
Intent intent = new Intent(getActivity(), MadePayment.class);
getActivity().startActivity(intent);
// end
Correct it as follows
/* Add this method in your host Activity */
public void attachFragment(Fragment fragment) {
if (null == fragment) {
return;
}
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragContainer, fragment);
/* add to back stack */
//ft.addToBackStack(null);
ft.commitAllowingStateLoss();
} catch (Exception e) {
}
}
And replace the fragmet
MadePayment fragment = new MadePayment;
MainActivity hostActivity= (MainActivity)getActivity();
hostActivity.attachFragment(homeFragment);
The MadePayment is a fragment. Use FragmentTransactions to replace the fragment.
Button button = (Button) getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment newfragment= new newFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentframe_container, newfragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by jamie on 9/12/2015.
*/
public class PlayersFragment extends DialogFragment {
ListView lv;
String[] players = {"arteta", "costa", "reid", "degea", "rooney", "terry"};
int[] images = {R.drawable.arteta, R.drawable.costa, R.drawable.reid, R.drawable.degea,
R.drawable.rooney, R.drawable.terry};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog, container, false);
//initialize listview
lv = (ListView) rootView.findViewById(R.id.listView1);
//set dialog title
getDialog().setTitle("Soccer SuperStars");
//create adapter obj and set list view to it
Adapter adapter = new Adapter(getActivity(), players, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Toast.makeText(getActivity(), players[pos], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Trying to create a ListView fragment in android studio and getting
error
cannot resolve method show(android.support.v4.app
FragmentManager,java.lang.string)
the error is on the p.show(fm,"Players Fragment) underlined in red, tried to resolve this but getting nowhere, i would really appreciate a solution to this! thank you
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
Button showBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm =getSupportFragmentManager();
final PlayersFragment p=new PlayersFragment();
showBtn=(Button)findViewById(R.id.button1);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
p.show(fm,"Players Fragment"); //error is here
}
});
}
}
I suppose you are using android.app.DialogFragment and not android.support.v4.app.DialogFragment. Just extend PlayersFragment from support library's android.support.v4.app.DialogFragment. Or, if you are not targeting old devices, you can change getSupportFragmentManager() to getFragmentManager()
You have to import android.support.v4.app.DialogFragment on the class PlayersFragment and then change getSupportFragmentManager() to getFragmentManager().
package com.example.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public static Sessions session;
public static EditText userNameFiled;
public static EditText passwordFiled;
public static Button loginBtn;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Sessions(getApplicationContext());
//status=session.PrefloginCheck();
if (session.PrefloginCheck()) {
Intent i = new Intent(MainActivity.this, Home.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(),
"User Login Status From Main Activity: " + session.PrefloginCheck(),
Toast.LENGTH_SHORT).show();
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements
View.OnClickListener {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
userNameFiled = (EditText) rootView.findViewById(R.id.userName);
passwordFiled = (EditText) rootView.findViewById(R.id.password);
loginBtn = (Button) rootView.findViewById(R.id.loginButton);
loginBtn.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View arg0) {
session.createLoginSession("login", "true");
session.createLoginSession("name", "uday");
session.createLoginSession("email", "********#gmail.com");
Intent i = new Intent(this.getActivity(), Home.class);
startActivity(i);
/*
* When i triggered the login button i want to kill the login activity
* */
//finish();
}
}
}
strong text
I am checking the login process in fragment class so
How to close the MainActivity When i move to the home after successfull login.
I am checking the login process in fragment class so
How to close the MainActivity When i move to the home after successfull login.
You can get access to the Fragment's current Activity with getActivity().
So you can use getActivity().finish();
To more understand more how fragments work, I created a mainactivity its layout has one<fragment>. and I created two java classes extend fragment and each of these classes has its own layout.
In the java class that extends fragment, I initailise my views textview inside onActivityCreated(), and as shown below in the code in the same class, i created two methods setbtnclicks(int clicks) and getbtnclicks(). From the mainactivity i assign number of clicks of a button to setbtnclicks() and i try to display the number of clicks on the textview of the class that extends fragment by calling getbtnclicks from inside onActivivtyCreated(). But the problem is, this method always displays zero, as if the number of clicks are not incremented.
MainActivtity:
//global variable
private int i = 0;
...
...
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment mSelectedFragment;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
switch (v.getId()) {
case R.id.btn00:
mSelectedFragment = new Fragment00();
mFragmentManager = getFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment00ID, mSelectedFragment);
mFragmentTransaction.commit();
mFragment00.setBtnClicks(i);
i++;
break;
Java_Class "Fragment00"
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated(): "+order);
order++;
mTv = (TextView) getView().findViewById(R.id.fragment00Tv00);
mTv.setText("the Button was clicked "+getBtnClicks()+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+getBtnClicks());
}
Once i have implemented a more or less same program like yours.The objective was to increment the number of button clicks in both the fragments.Here is the code.Hope it helps:
MainActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
public class MainActivity extends Activity implements OnClickListener{
Button btn1,btn2;
int click1=0,click2=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = null;
if (v == btn1) {
// do stuff for button left
click1++;
Bundle bundle=new Bundle();
String clickstring1=Integer.toString(click1);
bundle.putString("name1",clickstring1 );
fragment = new FragButton1();
fragment.setArguments(bundle);
}
if (v == btn2) {
// do stuff for button right
click2++;
Bundle bundle=new Bundle();
String clickstring2=Integer.toString(click2);
bundle.putString("name2",clickstring2 );
fragment = new FragButton2();
fragment.setArguments(bundle);
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
else{
Log.e("MainActivity", "Error in creating fragment");
}
}
}
FragButton1.java
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
#SuppressLint("NewApi")
public class FragButton1 extends Fragment{
TextView tv;
public FragButton1(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragbutton1, container, false);
String strtext=getArguments().getString("name1");
tv=(TextView)rootView.findViewById(R.id.tv_times1);
tv.setText(strtext);
return rootView;
}
}
FragButton2.java
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
#SuppressLint("NewApi")
public class FragButton2 extends Fragment{
TextView tv2;
public FragButton2(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragbutton2, container, false);
tv2=(TextView)rootView.findViewById(R.id.tv_times2);
String strtext=getArguments().getString("name2");
tv2.setText(strtext);
return rootView;
}
}
Here there are 2 buttons and onclick of a button a new fragment will be launched and the fragment will display the number of times a button is clicked in a textview.
increment i before the fragment Transaction
switch (v.getId()) {
case R.id.btn00:
i++;
mSelectedFragment = new Fragment00();
mFragmentManager = getFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment00ID, mSelectedFragment);
mFragmentTransaction.commit();
mFragment00.setBtnClicks(i);
break;