Open fragment with button from another fragment - java

I want to open another fragment using a button from another fragment.
This is the fragment with the button
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_myday, container, false);
Button buttonNext = (Button)view.findViewById(R.id.next);
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment someFragment = new TomorrowFragment();
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, someFragment);
fr.commit();
}
});
return view;
Fragment xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next to 2"
android:layout_centerInParent="true"
android:layout_alignParentRight="true"
android:id="#+id/next"/>
after I press the button nothing happens. I have followed code from other posts but nothing worked..

buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment someFragment = new TomorrowFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, someFragment);
fr.commitAllowingStateLoss();
}
});

Related

How to get input from EditText in android java fragment

I am trying to get user input using EditText from fragment after pressing a button. For some reason the button is clickable but no data from EditText.
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtUserInput"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/btnTest"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"/>
public class MainActivity extends AppCompatActivity {
TestFragment testFragment = new TestFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, testFragment)
.commit();
}
}
public class TestFragment extends Fragment {
Button btnTest;
EditText txtUserInput;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
btnTest = view.findViewById(R.id.btnTest);
txtUserInput = view.findViewById(R.id.txtUserInput);
String input = txtUserInput.getText().toString();
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
Add gettext() inside your click listener
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { String input=txtUserInput.getText().toString()
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
as you want data from edite text after clicking the button so once you click then on click event is triggered and then you should get data from edit field
you can do this thing like
and View is used to get root view for the fragment.
View view = inflater. Inflate(R.layout.fragment_test, container, false);
EditText editText = view.findViewById(R.id.txtUserInput);
Button btnTest = view.findViewById(R.id.btnTest);
String input ="";
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input=editText.getText().toString()
}
});

Android Dynamic Fragments

I have a activity with only 2 buttons and a FrameLayout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<Button
android:id="#+id/btPrincipal1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ver Fragment 1"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
/>
<Button
android:id="#+id/btPrincipal2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ver Fragment 2"
android:layout_gravity="center_horizontal"
android:layout_weight="1"/>
</LinearLayout>
<FrameLayout
android:layout_width="250dp"
android:layout_height="match_parent"
android:id="#+id/contenedor"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/linearLayout">
</FrameLayout>
When I click button 1, I call the fragment and, when I click button 2, I want to call the same fragment but with different properties. For example:
I click button 1 , call fragment A with background color green.
I click button 2 , call fragment A with background color red.
It's possible? and how can I do this? Thanks.
In your MainActivity, do:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.btPrincipal1);
Button button2 = (Button) findViewById(R.id.btPrincipal2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager supportFragmentManager = getSupportFragmentManager();
Bundle bundle = new Bundle();
bundle.putString(COLOR_PARAM, "green");
supportFragmentManager.beginTransaction()
.replace(R.id.contenedor, YourFragment.newInstance("Button1"))
.commit();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager supportFragmentManager = getSupportFragmentManager();
Bundle bundle = new Bundle();
bundle.putString(COLOR_PARAM, "red");
supportFragmentManager.beginTransaction()
.replace(R.id.contenedor, YourFragment.newInstance("Button2"))
.commit();
}
});
}
Then, in YourFragment.java, do:
public class YourFragment extends Fragment {
public static final String COLOR_PARAM = "param1";
private String currentColor;
public YourFragment() {}
public static Fragment newInstance(String param) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
args.putString(COLOR_PARAM, param);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
currentColor = getArguments().getString(COLOR_PARAM);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_layout);
if (currentColor.equals("green")) {
frameLayout.setBackgroundColor(getActivity().getResources().getColor(android.R.color.holo_green_dark));
}
else if (currentColor.equals("red")) {
frameLayout.setBackgroundColor(getActivity().getResources().getColor(android.R.color.holo_red_dark));
}
return view;
}
}
If you want to change the background just create and object of your fragment, and after clicking on buttons call a method to change the fragment background. but if you wanna to change fragments layout or other things create a new fragment cause of code readability.
try this:
public class FragmentA extends Fragment {
public static FragmentA newInstance(int colorResId) {
FragmentA fragment = new FragmentA();
Bundle bundle = new Bundle();
bundle.putInt("colorId", colorResId);
fragment.setArguments(bundle);
return new FragmentA();
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
int resId = getArguments().getInt("colorId", 0);
if (resId != 0) {
//set background
}
}
public void changeBackground(int colorId){
//set background
}
}

Layout inflation issues: Two layouts are inflated in a fragment, instead of one

I want to open a fragment from my activity, but when I do both the Activity layout and fragment layout is inflated, I only want the fragment layout to display. Why is this?
Activity Code:
public class Login extends Activity {
public static String res="";
private EditText login_username,login_pass;
private TextView test_login;
private SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btn_login = (Button) findViewById(R.id.btnLogin);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login(login_username.getText().toString(),login_pass.getText().toString());
}
});
private void login(final String user,String pass){
new Login_Server("http://192.168.1.100/test/index.php/client_users/Login",user,pass).execute();
final ProgressDialog pd=new ProgressDialog(Login.this);
pd.setMessage("Please Wait...");
pd.show();
final Timer tm=new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (res.equals("login")) {
Index index = new Index();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, index); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
tm.cancel();
res = "";
}
}
});
}
}, 1, 1500);
}
Fragment code:
public class Index extends Fragment implements View.OnClickListener {
private Button Index,Share;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.index, container, false);
Index=(Button)rootview.findViewById(R.id.index_page);
Share=(Button)rootview.findViewById(R.id.share_page);
btn_click();
return rootview;
}
public void btn_click(){
Index.setOnClickListener(this);
Share.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.share_page:
Share share_page = new Share();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, share_page); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
break;
}
}
}
xml layout fragment:
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:weightSum="100">
<include layout="#layout/main_index"></include>
<include layout="#layout/bottom_menu"></include>
</LinearLayout>
On your login activity
setContentView(R.layout.login);
inflates the activity layout
and on your fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.index, container, false);
Index=(Button)rootview.findViewById(R.id.index_page);
Share=(Button)rootview.findViewById(R.id.share_page);
btn_click();
return rootview;
}
inflates the fragment's layout
therefor you inflate 2 layouts
anyway if u wish to use the fragment layout allover the activity screen
u should change the activity layout to host a container with an ID
like in your code on the activity u have this line:
transaction.replace(android.R.id.content, index);
you should just have a view on the activity layout with the id=content and make it match_parent on height and width
this one should be the parent of all the other childs on the layout
that way the fragment will cover all of the activity layout when u replace the container
gl..

New fragment on button click from another fragment?

can anyone point me in the right direction and tell me what I'm doing wrong?
I have here a fragment with a button. When the button is pressed, it needs to replace the current fragment and load a new one. I've figured how to go from Fragment to Activity, and Activity to Fragment, just not Fragment to Fragment. I'm aware this question has been asked a few times but I'm just so new I couldn't figure it out myself.
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}
I think you are not initialising the FragmentManager. Without FragmentManager it is not possible to replace,update,create any fragment. Beacuse it is responsible replace or deleting any fragment. Hope this will help.
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}

ANDROID fragment inside a custom dialog in activity

I would like to put a fragment inside a custom dialog in activity.
I receive this error:
java.lang.IllegalArgumentException: No view found for id 0x7f0c007e (copyworld.rebootcw:id/container_schedule1) for fragment FragmentGiorno{418215c0 #0 id=0x7f0c007e}
This is my code:
layout.xml
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="#+id/spinner_dialog_schedulazione"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:id="#+id/container_schedule1">
</FrameLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Popup_schedule();
}
//******POPUP PER LA SCHEDULAZIONE******************
public void Popup_schedule() {
dialog_schedule=new Dialog(MainActivity.this);
dialog_schedule.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog_schedule.setContentView(R.layout.dialog_schedule);
dialog_schedule.setCancelable(false);
lp = new WindowManager.LayoutParams();
window = dialog_schedule.getWindow();
lp.copyFrom(window.getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog_schedule.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
window = dialog_schedule.getWindow();
window.setAttributes(lp);
FragmentGiorno fragment = new FragmentGiorno();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_schedule1, fragment);
fragmentTransaction.commit();
dialog_schedule.show();
}
}
How I add a fragment inside a custom dialog in MainActivity.java that extend Activity?
Try this
dialog_schedule.findViewById(R.id.container_schedule1)
Instead Of
R.id.container_schedule1
In your Code
If you want to load fragment inside dialog then you can use DialogFragment instead.
Below is the working example of using DialogFragment.
public class Demo extends DialogFragment{
View mainView;
LinearLayout layoutArrow;
Bundle bundle;
ArrayList<BookingDetail> bookingDetails;
View.OnClickListener onClickListener;
public static Demo newInstance(#NonNull ArrayList<BookingDetail> bookingDetails) {
Demo alertPopUpMapReservedBedInfo = new Demo();
Bundle args = new Bundle();
args.putSerializable("bookingDetails", bookingDetails);
alertPopUpMapReservedBedInfo.setArguments(args);
return alertPopUpMapReservedBedInfo;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, R.style.InvitationDialogWithSimpleAnim);
bundle = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.alert_info, container, false);
getDialog().setCanceledOnTouchOutside(true);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
layoutArrow = (LinearLayout) mainView.findViewById(R.id.layoutArrow);
FragmentGiorno fragment = new FragmentGiorno();
android.support.v4.app.FragmentTransaction fragmentTransaction =
this.getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_schedule1, fragment);
fragmentTransaction.commit();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if(onClickListener!=null){
onClickListener.onClick(null);
}
}
}
And call it by,
Demo newFragment = Demo.newInstance(bookingDetails);
newFragment.show(ft,"dialog");

Categories

Resources