I am trying to add a fragment dynamically to an activity. While on click fragment open sup its just with a white background.
Activity xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<FrameLayout
android:id="#+id/fragment_container"
android:name="SimpleFragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout="#layout/fragment_imageview">
</FrameLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
The fragment 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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
The fragment code
package com.example.wishkaro.mydhruvrecycle;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BlankFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_imageview, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
BlankFragment simpleFragment = BlankFragment.newInstance("Test1","Test2");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.add(R.id.fragment_container,
simpleFragment).addToBackStack(null).commit();
On click the fragment opens up with white background. And as its added to backstack back key gets handled as well. However the layout content of fragment are not be seen at all
Related
I'm having some difficulty facing the interactions between Fragments and between Fragments and my Activity, especially ClickListener-wise.
I'm developing a Calculator app composed of 2 fragments:
one Fragment contains all the Buttons (numbers and operators)
the other contains the 2 TextViews (operation and result)
The goal here is to make these two Fragments communicate between each other. I'm supposed to send characters and strings to a TextView until I click the on the "equals" button (on which I've put a ClickListener) but I can't seem to neither use the other buttons or send the information (it keeps warning me that the TextView is null, despite the interfaces).
This is the Fragment containing all the buttons and operators :
package fr.android.calculator.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import fr.android.calculator.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link LowerCalculatorFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link LowerCalculatorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class LowerCalculatorFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public LowerCalculatorFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LowerCalculatorFragment.
*/
// TODO: Rename and change types and number of parameters
public static LowerCalculatorFragment newInstance(String param1, String param2) {
LowerCalculatorFragment fragment = new LowerCalculatorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_lower_calculator, container, false);
Button button = new Button(getContext());
LinearLayout buttonContainer = view.findViewById(R.id.resultButtonFragment);
button.setText("=");
button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
button.setId(R.id.buttonEqualsFragment);
buttonContainer.addView(button);
button.setOnClickListener(v -> onButtonPressed(v));
return view;
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view,savedInstanceState);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(View view) {
if (mListener != null) {
mListener.lowerFragmentInteraction(view);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void lowerFragmentInteraction(View view);
}
}
<?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=".Activities.CalculatorSecondActivity"
android:id="#+id/frameLayout">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/numberOperators" android:baselineAligned="false">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/numbers" android:layout_weight="1">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent" android:id="#+id/SevenToPlus">
<Button
android:text="7"
android:layout_width="0dp"
android:layout_height="match_parent" android:id="#+id/button18" android:layout_weight="1"
android:onClick="onButtonClick"/>
<Button
android:text="8"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button19" android:layout_weight="1"
/>
<Button
android:text="9"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button20" android:layout_weight="1"
/>
<Button
android:text="+"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button21" android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent" android:id="#+id/FourToMinus">
<Button
android:text="4"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button22" android:layout_weight="1"
/>
<Button
android:text="5"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button23" android:layout_weight="1"
/>
<Button
android:text="6"
android:layout_width="0dp"
android:layout_height="match_parent" android:id="#+id/button24" android:layout_weight="1"
/>
<Button
android:text="-"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button25" android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_weight="1" android:id="#+id/OneToAsterix">
<Button
android:text="1"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button26" android:layout_weight="1"
/>
<Button
android:text="2"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button27" android:layout_weight="1"
/>
<Button
android:text="3"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button28" android:layout_weight="1"
/>
<Button
android:text="*"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button29" android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_weight="1">
<Button
android:text="0"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button32" android:layout_weight="1"
/>
<Button
android:text="/"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button33" android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/resultButtonFragment" android:layout_weight="4" android:orientation="vertical"
>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is the Fragment containing both TextViews :
package fr.android.calculator.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import fr.android.calculator.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link UpperCalculatorFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link UpperCalculatorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class UpperCalculatorFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView resultDisplay;
private TextView operations;
private OnFragmentInteractionListener mListener;
public UpperCalculatorFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UpperCalculatorFragment.
*/
// TODO: Rename and change types and number of parameters
public static UpperCalculatorFragment newInstance(String param1, String param2) {
UpperCalculatorFragment fragment = new UpperCalculatorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_upper_calculator, container, false);
operations = view.findViewById(R.id.operationsFragment);
resultDisplay = view.findViewById(R.id.resultDisplayFragment);
return view;
}
public void setOperationsText(String operationsText){
operations.setText(operationsText);
}
public void setResultDisplayText(String resultDisplayText){
resultDisplay.setText(resultDisplayText);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String operations) {
if (mListener != null) {
mListener.operationsFragmentInteraction(operations);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void operationsFragmentInteraction(String operations);
void resultDisplayFragmentInteraction(String resultDisplay);
}
}
<?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.UpperCalculatorFragment"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:background="#drawable/textview_border"
android:layout_marginRight="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/operationsFragment" android:layout_weight="2"/>
<TextView
android:background="#drawable/textview_border"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/resultDisplayFragment" android:layout_weight="3"/>
</LinearLayout>
</FrameLayout>
The activity itself that's in the middle is this one :
package fr.android.calculator.Activities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import fr.android.calculator.Fragments.LowerCalculatorFragment;
import fr.android.calculator.Fragments.UpperCalculatorFragment;
import fr.android.calculator.R;
import org.mozilla.javascript.Context;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class CalculatorSecondActivity extends AppCompatActivity implements LowerCalculatorFragment.OnFragmentInteractionListener, UpperCalculatorFragment.OnFragmentInteractionListener {
private LowerCalculatorFragment lowerCalculatorFragment;
private UpperCalculatorFragment upperCalculatorFragment;
private Context rhino = Context.enter(); // runtime environment
private TextView operations;
private Button value;
private String result;
private TextView resultDisplay;
private Handler handler;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
private String resp;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator_second);
lowerCalculatorFragment = LowerCalculatorFragment.newInstance("fragment", "you");
upperCalculatorFragment = UpperCalculatorFragment.newInstance("new fragment", "you 2");
getSupportFragmentManager().beginTransaction().add(R.id.lowerCalculator, lowerCalculatorFragment);
getSupportFragmentManager().beginTransaction().add(R.id.upperCalculator, upperCalculatorFragment);
getSupportFragmentManager().beginTransaction().commit();
}
#Override
public void operationsFragmentInteraction(String message) {
upperCalculatorFragment = (UpperCalculatorFragment) getSupportFragmentManager().findFragmentById(R.id.upperCalculator);
upperCalculatorFragment.setOperationsText(message);
}
#Override
public void resultDisplayFragmentInteraction(String message) {
upperCalculatorFragment = (UpperCalculatorFragment) getSupportFragmentManager().findFragmentById(R.id.upperCalculator);
upperCalculatorFragment.setResultDisplayText(message);
}
#Override
public void lowerFragmentInteraction(View view) {
value = view.findViewById(view.getId());
System.out.println("Value : " + value.getText());
if (value != view.findViewById(R.id.buttonEqualsFragment)) {
System.out.println("Value : " + value.getText());
operationsFragmentInteraction((String) value.getText());
} else {
// Avec Async
new AsyncTaskRunner().execute((String) operations.getText());
/* Avec Handler*/
//calculate((String) operations.getText());
}
}
public void onButtonClick(View view){
lowerCalculatorFragment.onButtonPressed(view);
}
public void calculate(String operations) {
Runnable runnable = () -> {
try {
socket = new Socket("10.0.2.2", 9876);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(operations);
result = dataInputStream.readUTF();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
handler.post(() -> resultDisplay.setText(result));
};
new Thread(runnable).start();
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
socket = new Socket("10.0.2.2", 9876);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(params[0]);
result = dataInputStream.readUTF();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(params[0]); // Calls onProgressUpdate()
resp = "Slept for " + 5 + " seconds";
return resp;
}
protected void onProgressUpdate(String... text) {
resultDisplayFragmentInteraction(result);
}
}
}
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_calculator_second"
tools:context=".Activities.CalculatorSecondActivity">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="5">
<fragment android:layout_width="match_parent" android:layout_height="119dp"
android:name="fr.android.calculator.Fragments.UpperCalculatorFragment"
android:id="#+id/upperCalculator"
tools:layout="#layout/fragment_upper_calculator"
android:layout_weight="1"/>
<fragment android:name="fr.android.calculator.Fragments.LowerCalculatorFragment"
android:layout_width="409dp" android:layout_height="413dp"
android:id="#+id/lowerCalculator" tools:layout="#layout/fragment_lower_calculator"
android:layout_weight="4"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Do you guys have any ideas why?
Thanks in advance,
Fares.
EDIT : I've added methods to my Fragments after the wise advice from Edgar. If I understood correctly, the interfaces allow us to fetch the informations, that will be used in the methods of the fragments. However even though I've added ClickListeners to my buttons, only the buttonEqualsFragmentis "listened" to.
Even if I debug unless I click on the buttonEqualsFragment the other buttons aren't taken in account.
I created a method in the Activity to do that called the Fragment's implemented interface. (onButtonClick)
The problem is you are trying to display the info in the activity and not in the fragment. Try the following suggestions.
In yourUpperCalculatorFragment class place this at the top:
private Textview operations, results;
then in onCreateView() add the following to ensure the textviews are not null:
operations = view.findViewById(R.id.operationsFragment);
results = view.findViewById(R.id.resultDisplayFragment);
Next you have to define a public method still in this fragment (UpperCalculatorFragment) that will handle information from the Activity. I only show result you need another for operation as well
public void displayResult(String result){
results.setText(result);//this displays the result on textview
}
To display the result/operation you have to call that method from the CalculatorSecondActivity like so;
public void displayResultInFragment(String message) {
UpperCalculatorFragment upperFrag =
(UpperCalculatorFragment) getSupportFragmentManager()
.findFragmentById(R.id.upperCalculator);
//show the result here after all calculation
upperFrag.displayResult(message);
}
please refer to this android developers docs
I'm developing an app with many fragments and each fragment has a button by default in the top-left corner. When I press that small button nothing happens. How can I remove it?
Thanks!
I didn't try anything, but I was thinking that I have to remove the onButtonPressed method, but I'm not sure
This is the code of a fragment
package com.flixarts.ar.*;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link schoolfragment0.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link schoolfragment0#newInstance} factory method to
* create an instance of this fragment.
*/
public class schoolfragment0 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public schoolfragment0() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment schoolfragment0.
*/
// TODO: Rename and change types and number of parameters
public static schoolfragment0 newInstance(String param1, String param2) {
schoolfragment0 fragment = new schoolfragment0();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_schoolfragment0, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I want to delete the button that's grey in the top left corner
This is the XML
<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=".schoolfragment0">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/espacioFrases"
android:layout_width="325dp"
android:layout_height="111dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:text=""
android:textColor="#color/ColorPrimary"
android:textSize="36sp" />
<TextView
android:id="#+id/espacioFrasesTraducidas"
android:layout_width="307dp"
android:layout_height="103dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="360dp"
android:text=""
android:textColor="#color/ColorPrimary"
android:textSize="36sp" />
</FrameLayout>
In the XML I have two textviews (I've covered, sorry, I can't find where is that button)
So what I want to do is something like this
Select a item from NavigationView
remove activity_main's content
load and show the fragment I've selected
For example:
I selected "Homepage" in NavigationView which should load Homepage.class
Load the fragment_homepage.xml
remove everything in activity_main.xml
What I am getting trouble is, no matter what I've selected in NavigationView, it shows up BOTH fragment_(whatIhaveSelected).xml and activity.xml which I don't want to.
Code:
MainActivity class
package to.epac.factorycraft.drawerlayouttest;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navigationView);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
int id = item.getItemId();
Fragment myFragment = null;
Class fragmentClass = null;
switch (id) {
case R.id.homepage:
fragmentClass = Homepage.class;
break;
case R.id.station:
fragmentClass = Station.class;
break;
default:
fragmentClass = Homepage.class;
navigationView.setCheckedItem(R.id.homepage);
Toast.makeText(MainActivity.this, "default Homepage clicked", Toast.LENGTH_LONG).show();
break;
}
try {
myFragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.flcontent, myFragment).commit();
item.setCheckable(true);
setTitle(item.getTitle());
drawerLayout.closeDrawers();
// TODO
// If first open app, it will show "app_name", but when clicked on "Homepage", it will show "主頁", waiting to fix
toolbar.setTitle(item.getTitle());
return true;
}
});
}
#Override
public void onBackPressed() {
if (this.drawerLayout.isDrawerVisible(GravityCompat.START)) {
this.drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="to.epac.factorycraft.drawerlayouttest.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="#string/app_name" />
<FrameLayout
android:id="#+id/flcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="activity_main's textView" />
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Homepage class
package to.epac.factorycraft.drawerlayouttest;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Homepage.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Homepage#newInstance} factory method to
* create an instance of this fragment.
*/
public class Homepage extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Homepage() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Homepage.
*/
// TODO: Rename and change types and number of parameters
public static Homepage newInstance(String param1, String param2) {
Homepage fragment = new Homepage();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_homepage, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
fragment_homepage.xml
<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"
tools:context="to.epac.factorycraft.drawerlayouttest.Homepage"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Homepage Fragment" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
I am trying to start a new fragment when a textView is presses. I have tried alternative methods but still the onClickListener is not working. I have no crashes, nothing. I have also tried with buttons, or creating the onClick method in the OncreateView method and setting a listener.
Fragment:package georgia.languagelandscape.fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import georgia.languagelandscape.R;
//import android.support.v4.app.Fragment;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ProfileFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ProfileFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HelpFragment extends Fragment implements MyProjectsFragment.OnFragmentInteractionListener, View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private FragmentManager fm = null;
private FragmentTransaction ft = null;
private OnFragmentInteractionListener mListener;
public HelpFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
public static HelpFragment newInstance(String param1, String param2) {
HelpFragment fragment = new HelpFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://www.youtube.com/embed/lY2H2ZP56K4\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
View rootview = inflater.inflate(R.layout.fragment_help, container, false);
TextView tv= (TextView) rootview.findViewById(R.id.item1);
tv.setFocusableInTouchMode(false);
tv.setOnClickListener(this);
/* WebView display = (WebView) rootview.findViewById(R.id.webView);
display.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = display.getSettings();
webSettings.setJavaScriptEnabled(true);
display.loadData(frameVideo, "text/html", "utf-8");*/
return inflater.inflate(R.layout.fragment_help, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.item1:
MyProjectsFragment myProjectsFragment= new MyProjectsFragment();
fm = getFragmentManager();
ft = fm.beginTransaction();
Log.d("dcf","da");
ft.replace(R.id.content_replace, myProjectsFragment);
ft.commit();
break;
/*case R.id.item2:
//Do what you want for create_button
break;
default:
break;*/
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
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="georgia.languagelandscape.fragments.HelpFragment"
android:background="#android:color/background_light"
tools:background="#android:color/white">
<TextView
android:text="Help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:id="#+id/textView"
android:textSize="30sp"
android:textStyle="normal|bold"
android:textColor="#000"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:id="#+id/item1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:text="item1"
android:clickable="true" />
<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_marginTop="100dp"
android:padding="10dp"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
You have one view called rootview. and you are returning ANOTHER view when you do return inflater.inflate(R.layout.fragment_help, container, false); at the end.
Replace:
return inflater.inflate(R.layout.fragment_help, container, false);
With:
return rootview;
That's it.
I'm having a problem with an app that I'm making with the main activity set as navigation drawer activity,
What I'm getting is that when i press an item in the navigation list, the fragment is not being replaced by the corresponding fragment.
The code for the replacement is the following:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment objFragment = null;
if (id == R.id.nav_dashboard) {
objFragment = new Dashboard_fragment();
} else if (id == R.id.nav_myschedule){
objFragment = new Schedule_fragment();
} else if (id == R.id.nav_rides) {
objFragment = new Rides_fragment();
} else if (id == R.id.nav_vouchers) {
objFragment = new Vouchers_fragment();
} else if (id == R.id.nav_help) {
objFragment = new Help_fragment();
} else if (id == R.id.nav_settings) {
objFragment = new Settings_fragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, objFragment)
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
where each fragment is the following:
package com.example.user.greenmiles;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Dashboard_fragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Dashboard_fragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class Dashboard_fragment extends Fragment {
private OnFragmentInteractionListener mListener;
public static Dashboard_fragment newInstance() {
Dashboard_fragment fragment = new Dashboard_fragment();
return fragment;
}
public Dashboard_fragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Dashboard");
return inflater.inflate(R.layout.fragment_dashboard_fragment, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
And where the xml file corresponding to the main activity is the following:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include layout="#layout/app_bar_main" android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main" app:menu="#menu/activity_main_drawer" />
and the xml file corresponding to the fragments is the following:
<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="com.example.user.greenmiles.Dashboard_fragment">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="Dashboard"
android:textSize="16pt" />
Please I have been stuck in this for a couple of days without being able to solve it.
Thanks a lot
I've found the answer finally, it was not related to the coding, but instead to the xml file. The problem is specifically with the following block:
<include layout="#layout/app_bar_main" android:layout_width="match_parent"
android:layout_height="match_parent" />
The height property is taking all the space in the fragment, and this the included fragment in the frame layout wasn't showing. A modification can be done by changing match_parent to wrap_content and it will be solved.
Thank you guys anyways