Interaction betweens Fragments and Activity - android

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

Related

Fragemnt is empty

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

OnClickListener not working for textview

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.

How to animate overlay an edit-box on tab-layout on android?

I wanted to achieve this animation, which is the search edit box overlays the tab-layout, I must tell that I tried this code on the parent layout android:animateLayoutChanges="true" and set the tab-layout visibility to View.GONE but it just animates the tab moving up, not the search box overlays tab-layout.
I have made a quick dummy app that looks like yours, and tried to achieve what you have shown in your animation. See the effect below (you can make it more smooth and elegant) :
Its a bit tricky way of doing, the way I have done. I post my whole code here :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pabhinav.testapp3">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.pabhinav.testapp3;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import static com.pabhinav.testapp3.R.id.container;
public class MainActivity extends AppCompatActivity implements PlaceholderFragment.OnSearchBoxClick{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
/**
* Search Box in activity.
*/
private RelativeLayout dummySearchBox;
private LinearLayout topSearchBox;
/**
* Overlay View appears when search box is clicked.
*/
private View overlay;
/**
* Back button image view for top search box
*/
private ImageView backButtonSearchBox;
/**
* PlaceHolderFragment saved only for second tab,
* which has search box.
*/
private PlaceholderFragment placeholderFragment;
private float xDelta, yDelta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
overlay = findViewById(R.id.overlay_whole_page);
backButtonSearchBox = (ImageView)findViewById(R.id.search_icon);
// Consume touch event, so that it does not pass to parent views.
// This is done to block swipe events of tab layout, once search
// box is clicked.
overlay.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
// TabLayout and ViewPager.
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(container);
dummySearchBox = (RelativeLayout)findViewById(R.id.dummy_search_box);
topSearchBox = (LinearLayout)findViewById(R.id.top_search_box);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if(i == position){
tabLayout.getTabAt(i).setIcon(getTabIconHighlighted(i));
} else {
tabLayout.getTabAt(i).setIcon(getTabIconUnhighlighted(i));
}
}
}
#Override
public void onPageScrollStateChanged(int state) {}
});
// Setup viewpager with tablayout and also set up icons of each tabs :
tabLayout.setupWithViewPager(mViewPager);
for(int i = 0; i<tabLayout.getTabCount(); i++){
// Set first tab highlighted :
if(i == 0){
tabLayout.getTabAt(i).setIcon(getTabIconHighlighted(i));
} else {
tabLayout.getTabAt(i).setIcon(getTabIconUnhighlighted(i));
}
}
// Back Button in top search box clicked.
backButtonSearchBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
overlay.setVisibility(View.INVISIBLE);
dummySearchBox.setVisibility(View.VISIBLE);
topSearchBox.setVisibility(View.INVISIBLE);
AnimationSet animSet = new AnimationSet(true);
animSet.setFillAfter(false);
animSet.setDuration(150);
animSet.setInterpolator(new LinearInterpolator());
TranslateAnimation translate = new TranslateAnimation(-xDelta, 0, -yDelta, 0);
animSet.addAnimation(translate);
ScaleAnimation scale = new ScaleAnimation(1.2f, 1f, 1.2f, 1f);
animSet.addAnimation(scale);
dummySearchBox.startAnimation(animSet);
animSet.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
placeholderFragment.showSearchLayout();
dummySearchBox.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
}
private int getTabIconUnhighlighted(int position){
switch (position){
case 0 : return R.drawable.ic_home_black_24dp;
case 1 : return R.drawable.ic_search_black_24dp;
case 2 : return R.drawable.ic_heart_black_24dp;
case 3 : return R.drawable.ic_view_headline_black_24dp;
}
return -1;
}
private int getTabIconHighlighted(int position){
switch(position){
case 0 : return R.drawable.ic_home_highlighted_24dp;
case 1 : return R.drawable.ic_search_highlighted_24dp;
case 2 : return R.drawable.ic_heart_highlighted_24dp;
case 3 : return R.drawable.ic_view_headline_highlighted_24dp;
}
return -1;
}
/**
* This event is when search box from fragment is clicked,
* need to animate the search box present in activity
* to reach the top of activity display.
*/
#Override
public void onClick() {
dummySearchBox.setVisibility(View.VISIBLE);
dummySearchBox.clearFocus();
((EditText)findViewById(R.id.search_edit_text)).clearFocus();
performAnimation(dummySearchBox);
}
public void performAnimation(final RelativeLayout dummySearchBox){
if(xDelta == 0 && yDelta == 0){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int[] originalPos = new int[2];
dummySearchBox.getLocationOnScreen(originalPos);
xDelta = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18, getResources().getDisplayMetrics());
yDelta = originalPos[1] - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getResources().getDisplayMetrics());;
}
AnimationSet animSet = new AnimationSet(true);
animSet.setFillAfter(false);
animSet.setDuration(200);
animSet.setInterpolator(new LinearInterpolator());
TranslateAnimation translate = new TranslateAnimation( 0, -1*xDelta, 0, -1*yDelta);
animSet.addAnimation(translate);
ScaleAnimation scale = new ScaleAnimation(1f, 1.15f, 1f, 1.15f);
animSet.addAnimation(scale);
dummySearchBox.startAnimation(animSet);
animSet.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
topSearchBox.setVisibility(View.VISIBLE);
dummySearchBox.setVisibility(View.INVISIBLE);
overlay.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment.
PlaceholderFragment placeholderFragment = new PlaceholderFragment();
placeholderFragment.setOnSearchBoxClick(MainActivity.this);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position + 1);
placeholderFragment.setArguments(args);
if(position == 1){
MainActivity.this.placeholderFragment = placeholderFragment;
}
return placeholderFragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
}
PlaceholderFragment.java
package com.pabhinav.testapp3;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* #author pabhinav
*/
public class PlaceholderFragment extends Fragment {
private LinearLayout searchLayout;
public PlaceholderFragment() {
}
private OnSearchBoxClick onSearchBoxClick;
public void setOnSearchBoxClick(OnSearchBoxClick onSearchBoxClick){
this.onSearchBoxClick = onSearchBoxClick;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int sectionNumber = getArguments().getInt(MainActivity.SectionsPagerAdapter.ARG_SECTION_NUMBER);
View rootView = inflater.inflate((sectionNumber == 2) ? R.layout.fragment_search : R.layout.fragment_main, container, false);
if(sectionNumber != 2) {
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, sectionNumber));
} else {
// Its the fragment with search box :
TextView searchText = (TextView) rootView.findViewById(R.id.search_text);
ImageView searchIcon = (ImageView)rootView.findViewById(R.id.search_icon);
searchLayout = (LinearLayout)rootView.findViewById(R.id.search_linear_layout);
// Need to do transition when clicked on any of the search box elements :
View.OnClickListener clickListener = new View.OnClickListener(){
#Override
public void onClick(View v) {
searchLayout.setVisibility(View.INVISIBLE);
if(onSearchBoxClick != null)
onSearchBoxClick.onClick();
}
};
searchText.setOnClickListener(clickListener);
searchLayout.setOnClickListener(clickListener);
searchIcon.setOnClickListener(clickListener);
}
return rootView;
}
public void showSearchLayout(){
searchLayout.setVisibility(View.VISIBLE);
}
public interface OnSearchBoxClick{
public void onClick();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.pabhinav.testapp3.MainActivity">
<android.support.design.widget.TabLayout
android:layout_marginTop="8dp"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- Top Search Box -->
<!-- Only appears when search box is clicked -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="#+id/top_search_box"
android:visibility="invisible"
android:orientation="horizontal">
<RelativeLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<ImageView
android:gravity = "center"
android:layout_width="52dp"
android:paddingLeft="24dp"
android:paddingRight="8dp"
android:id="#+id/search_icon"
android:layout_height="match_parent"
android:src="#drawable/ic_arrow_back_black_24dp"/>
<EditText
android:layout_toEndOf="#+id/search_icon"
android:hint="#string/search_soundcloud"
android:textSize="18sp"
android:background="#android:color/transparent"
android:textColorHint="#B3B3B3"
android:layout_margin="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
<!-- Dummy container for search box -->
<!-- This will do transition from its location to top_search_box location -->
<RelativeLayout
android:id="#+id/dummy_search_box"
android:layout_width="match_parent"
android:layout_below="#+id/tabs"
android:visibility="invisible"
android:layout_height="wrap_content"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="#+id/search_linear_layout_dummy"
android:orientation="horizontal">
<RelativeLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#android:color/white"
android:elevation="2dp"
android:translationZ="2dp">
<ImageView
android:gravity = "center"
android:layout_width="20dp"
android:layout_marginStart="16dp"
android:id="#+id/search_icon_dummy"
android:layout_height="match_parent"
android:src="#drawable/ic_search_light_black_24dp"/>
<EditText
android:id="#+id/search_edit_text"
android:layout_toEndOf="#+id/search_icon_dummy"
android:hint="#string/search_soundcloud"
android:textSize="16sp"
android:background="#android:color/transparent"
android:textColorHint="#B3B3B3"
android:layout_margin="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
<android.support.v4.view.ViewPager
android:layout_below="#+id/tabs"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Dummy overlay over whole page, More things can be added like listview
which displays result of searched text -->
<View
android:id="#+id/overlay_whole_page"
android:layout_below="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:background="#72000000" />
<!-- Dummy shadow below tablayout -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/tabs"
android:background="#42000000" />
</RelativeLayout>
fragment_search.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.pabhinav.testapp3.MainActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="#+id/search_linear_layout"
android:orientation="horizontal">
<RelativeLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#android:color/white"
android:elevation="2dp"
android:translationZ="2dp">
<ImageView
android:gravity = "center"
android:layout_width="20dp"
android:layout_marginStart="16dp"
android:id="#+id/search_icon"
android:layout_height="match_parent"
android:src="#drawable/ic_search_light_black_24dp"/>
<TextView
android:id="#+id/search_text"
android:layout_toEndOf="#+id/search_icon"
android:text="#string/search_soundcloud"
android:gravity="center_vertical"
android:textColor="#B3B3B3"
android:textSize="16sp"
android:layout_margin="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
<TextView
android:id="#+id/suggested_stations"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:textSize="18sp"
android:layout_below="#+id/search_linear_layout"
android:text = "#string/suggested_stations"/>
<LinearLayout
android:layout_below="#+id/suggested_stations"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="240dp"
android:src="#drawable/image_1"
android:layout_weight="1"/>
<ImageView
android:layout_marginStart="16dp"
android:layout_width="0dp"
android:layout_height="240dp"
android:src="#drawable/image_2"
android:layout_weight="1"/>
</LinearLayout>
</RelativeLayout>
Download the whole project from here : https://drive.google.com/file/d/0B_Mi44NWLWmyNFNkeHJ6cVBLTTg/view?usp=sharing
Hope it helps !

Why text in TextView doesn't update when button pressed on fragment?

I created my app with the Tabbed Activity. I created some fragments and simple UI. Swipe and tabs work. I want to make really simple calculator-like app but I can't even change the text.
I tried so many solutions found on the Internet, but nothing works. I'm a beginner in Android development and now my code is a real mess.
What change to make it work? I just want to change some TextView's texts after clicking calculate button.
SingleLeg.java
package com.mycompany.hoptestcalculator;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
//import android.text.Editable;
//import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
//import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SingleLeg.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SingleLeg#newInstance} factory method to
* create an instance of this fragment.
*/
public class SingleLeg 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;
/**
* 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 SingleLeg.
*/
// TODO: Rename and change types and number of parameters
public static SingleLeg newInstance(String param1, String param2) {
SingleLeg fragment = new SingleLeg();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public SingleLeg() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// ImageButton calculate = (ImageButton) getView().findViewById(R.id.calculate);
//
//
// calculate.setOnClickListener(this);
}
// #Override
// public void onClick(View v) {
// int id = v.getId();
//
//
// left1 = (EditText) getView().findViewById(R.id.LeftTr1);
// right1 = (EditText) getView().findViewById(R.id.RightTr1);
// left2 = (EditText) getView().findViewById(R.id.LeftTr2);
// right2 = (EditText) getView().findViewById(R.id.RightTr2);
//
// if(id == R.id.calculate && (!left1.getText().equals("")) ) {
// avgL.setText("2");
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_single_leg, container, false);
View v = inflater.inflate(R.layout.fragment_single_leg,
container, false);
Button calculate = (Button) getView().findViewById(R.id.calculate);
final TextView textView = (TextView) getView().findViewById(R.id.avgLeft);
calculate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
textView.setText("abc");
}
});
return v;
}
//
// EditText left1 = (EditText) getView().findViewById(R.id.LeftTr1);
// EditText right1 = (EditText) getView().findViewById(R.id.RightTr1);
// EditText left2 = (EditText) getView().findViewById(R.id.LeftTr2);
// EditText right2 = (EditText) getView().findViewById(R.id.RightTr2);
// TextView avgL; //= (TextView) getView().findViewById(R.id.avgLeft);
// TextView avgR = (TextView) getView().findViewById(R.id.avgRight);
// TextView leftOfRight = (TextView) getView().findViewById(R.id.Left_Right);
// TextView rightOfLeft = (TextView) getView().findViewById(R.id.Right_Left);
// 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);
}
// //Declaration
// private class GenericTextWatcher implements TextWatcher{
//
// private View view;
// private GenericTextWatcher(View view) {
// this.view = view;
// }
//
// public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
// public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//
// public void afterTextChanged(Editable editable) {
// String text = editable.toString();
// switch(view.getId()){
// case R.id.LeftTr1:
// text.setName(text);
// break;
// case R.id.RightTr1:
// model.setEmail(text);
// break;
// case R.id.LeftTr2:
// model.setPhone(text);
// break;
// }
// }
// }
// left1.addTextChangedListener(new TextWatcher() {
// #Override
// public void afterTextChanged(Editable arg0) {
// enableSubmitIfReady();
// }
//
// #Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// }
//
// #Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
// }
// });
public void updateTextView(String toThis) {
TextView avg = (TextView) getView().findViewById(R.id.avgLeft);
avg.setText("567");
return;
}
}
fragment_single_leg.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.mycompany.hoptestcalculator.SingleLeg"
android:id="#+id/container"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<View
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/left_leg"
android:id="#+id/textView"
android:background="#drawable/back"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/right_leg"
android:id="#+id/textView2"
android:background="#drawable/back"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="10dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/trial_1"
android:id="#+id/trial1" />
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/LeftTr1"
android:layout_gravity="center_horizontal" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/RightTr1"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/trial_2"
android:id="#+id/trial2" />
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/LeftTr2"
android:layout_gravity="center_horizontal" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/RightTr2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/average"
android:id="#+id/avg" />
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/avgLeft"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg"
android:text="rgrrgrgrg"
android:enabled="true"
android:editable="false" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/avgRight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/left_of_right"
android:id="#+id/lofR"
android:layout_gravity="center_vertical"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/Left_Right"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="10dp"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/right_of_left"
android:id="#+id/RofL"
android:layout_gravity="center_vertical"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/Right_Left"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="#+id/calculate"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:textSize="35dp" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.hoptestcalculator" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Inside onCreateView() of the fragment :
Button calculate = (Button) convertView.findViewById(R.id.calculate);
final TextView textView = (TextView) convertView.findViewById(R.id.textViewId);
Then set a click listener on the button. :
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("Here goes sample text");
}
});

Android Fragments showing irregular behavior

I have multiple fragments in my Activity. It should initiate only first fragment at start up. It initializes the second one also. More over I move from one fragment to the other though a swipe action. When I swipe from first fragment to the next, third in the row is also initiated.
I have to get data from the server and then populate that fragment. Network request is sent but not for the one for which I am sending but for the fragment next to it.
Please suggest me where I am mistaken...
Thanks in advance.
Following is the code:
Note: Sample code is being used, Please consider the other fragments and their layouts as the same as that for Fragment1.
Main Activity
package com.example.fragments;
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements OnClickListener {
/**
* Constants for tabs
*/
public static final int TAB_SCORES = 0;
public static final int TAB_PAVILION = 1;
public static final int TAB_FRIENDS = 2;
public static final int TAB_OTHER = 3;
public static final int TAB_CROWD = 4;
public static final int TAB_SOCIAL = 5;
private List<Fragment> fragments=null;
private FragmentsAdaptor _adapter;
/** The context object. */
public static Object contextObject = null;
private TableLayout scoresTab, socialTab, pavilionTab, friendsTab, othersTab, crowdTab;
private TextView mScoresTv, mPavilionTv, mFriendsTv, mOtherTv, mCrowdTv, mSocialTv;
private HorizontalScrollView tabsLayout;
private int fragmentPosition;
public ViewPager mViewPager;
private int moveRight = 100;
#Override
protected void onStart() {
super.onStart();
}
/**
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mViewPager = (ViewPager)findViewById(R.id.viewPager);
setViews();
addListeners();
setTab();
addFragments();
}
private void setViews() {
scoresTab = (TableLayout)findViewById(R.id.scores_tab);
pavilionTab = (TableLayout)findViewById(R.id.pavilion_tab);
friendsTab = (TableLayout)findViewById(R.id.friends_tab);
othersTab = (TableLayout)findViewById(R.id.others_tab);
crowdTab = ((TableLayout)findViewById(R.id.crowd_tab));
socialTab = (TableLayout)findViewById(R.id.social_tab);
tabsLayout = (HorizontalScrollView)findViewById(R.id.tabs_layout);
mScoresTv = (TextView)findViewById(R.id.scores);
mPavilionTv = (TextView)findViewById(R.id.pavilion);
mFriendsTv = (TextView)findViewById(R.id.friends);
mOtherTv = (TextView)findViewById(R.id.other);
mCrowdTv = (TextView)findViewById(R.id.crowd);
mSocialTv = (TextView)findViewById(R.id.social);
}
private void addListeners() {
mScoresTv.setOnClickListener(MainActivity.this);
mPavilionTv.setOnClickListener(MainActivity.this);
mFriendsTv.setOnClickListener(MainActivity.this);
mOtherTv.setOnClickListener(MainActivity.this);
mCrowdTv.setOnClickListener(MainActivity.this);
mSocialTv.setOnClickListener(MainActivity.this);
}
private void addFragments(){
fragments = new Vector<Fragment>();
fragments.add(new Fragment1(this));
fragments.add(new Fragment2(this));
fragments.add(new Fragment3(this));
fragments.add(new Fragment4(this));
fragments.add(new Fragment5(this));
fragments.add(new Fragment6(this));
this._adapter = new FragmentsAdaptor(super.getSupportFragmentManager(), fragments);
mViewPager.setAdapter(this._adapter);
}
#Override
public void onClick(View v){
onTabsClick(v);
}
public void onTabsClick(View v) {
//reset layout of all the text views
resetlayouts();
if(v == mScoresTv) {
if(mViewPager.getCurrentItem() != TAB_SCORES) {
changeTab(TAB_SCORES);
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mCrowdTv) {
if(mViewPager.getCurrentItem() != TAB_CROWD) {
changeTab(TAB_CROWD);
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mFriendsTv) {
if(mViewPager.getCurrentItem() != TAB_FRIENDS) {
changeTab(TAB_FRIENDS);
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mOtherTv) {
if(mViewPager.getCurrentItem() != TAB_OTHER) {
changeTab(TAB_OTHER);
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mPavilionTv) {
if(mViewPager.getCurrentItem() != TAB_PAVILION) {
changeTab(TAB_PAVILION);
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mSocialTv) {
if(mViewPager.getCurrentItem() != TAB_SOCIAL) {
changeTab(TAB_SOCIAL);
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
}
}
}
private void changeTab(int tabType) {
mViewPager.setCurrentItem(tabType);
System.out.println("tab to change to: " + tabType);
}
private void resetlayouts(){
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
othersTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
socialTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
mScoresTv.setTextColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.black));
}
private void setTab() {
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
System.out.println("setTab:::::::::::::::::::::::::::::::::::" + position);
int previousFragment = fragmentPosition;
if(previousFragment < position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() + moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
if(previousFragment > position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() - moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
fragmentPosition = position;
resetlayouts();
System.out.println("In on tab change listener!");
switch(position) {
case TAB_SCORES:
System.out.println("scores");
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
case TAB_PAVILION:{
System.out.println("pavilion");
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_FRIENDS:{
System.out.println("friends");
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_OTHER:{
System.out.println("others");
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_CROWD:{
System.out.println("crowd");
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_SOCIAL:{
System.out.println("social");
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
}
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null)
fragment.onPause();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
FragmentsAdapter
package com.example.fragments;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentsAdaptor extends FragmentPagerAdapter {
private List<Fragment> fragments;
/**
* #param fm
* #param fragments
*/
public FragmentsAdaptor(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.fragments.size();
}
public Fragment getFragment(int position) {
return this.fragments.get(position);
}
}
Fragment1
package com.example.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
public class Fragment1 extends Fragment implements OnClickListener {
private Context context;
public Fragment1() {}
public Fragment1(Context contex) {
this.context=contex;
}
#Override
public void onClick(View arg0) {
}
#Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
System.out.println("Fragment1.onInflate() called................");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
System.out.println("Fragment1.onAttach() called................");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Fragment1.onCreate() called................");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
System.out.println("Fragment1.onCreateView() called................");
View root = (View) inflater.inflate(R.layout.fragment1_screen, null);
updateArticleView(root);
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("Fragment1.onActivityCreated() called................");
}
#Override
public void onStart() {
super.onStart();
System.out.println("Fragment1.onStart() called................");
}
#Override
public void onResume() {
super.onResume();
System.out.println("Fragment1.onResume() called................");
}
#Override
public void onPause() {
super.onPause();
System.out.println("Fragment1.onPause() called................");
onDestroyView();
}
#Override
public void onDestroyView() {
super.onDestroyView();
System.out.println("Fragment1.onDestroyView() called................");
onDestroy();
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Fragment1.onDestroy() called................");
onDetach();
}
#Override
public void onDetach() {
super.onDetach();
System.out.println("Fragment1.onDetach() called................");
}
public void updateArticleView(View view) {
}
}
Main Activity Layout
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<HorizontalScrollView
android:id="#+id/tabs_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="2dp"
android:paddingRight="2dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<!-- First Tab -->
<TableLayout
android:id="#+id/scores_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/scores"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Scores"
android:textColor="#android:color/white"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Second Tab -->
<TableLayout
android:id="#+id/pavilion_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/pavilion"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="25dp"
android:text="Pavilion"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Third Tab -->
<TableLayout
android:id="#+id/friends_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/friends"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Friends"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fourth Tab -->
<TableLayout
android:id="#+id/others_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/other"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Other"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fifth Tab -->
<TableLayout
android:id="#+id/crowd_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/crowd"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Crowd"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="0px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Sixth Tab -->
<TableLayout
android:id="#+id/social_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/social"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Social"
android:textColor="#android:color/black"
android:textSize="12sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</HorizontalScrollView>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#id/tabs_layout"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" >
</android.support.v4.view.ViewPager>
Fragment layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relLay"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/text1"
android:text="Fragment1 Text"
android:textColor="#android:color/black"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I achieved it by placing the following code at the end of OnPageChangeListener.onPageSelected()
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null) {
fragment.onPause();
}
I am using onPause() in the following way
public void onPause(){
super.onPause();
onDestroyView();
}
public void onDestroyView() {
super.onDestroyView();
onDestroy();
}
public void onDestroy() {
super.onDestroy();
onDetach();
}
public void onDetach() {
super.onDetach();
}
this is a known issue, that ViewPager(FragmentAdapter(Fragements)) created and destroyed according to the actual page.
I also came across with this situation, furthermore the data (Object) not referenced, because of a destroy will be collected by the GC so this is difficult.
I would use a static object at the main Activity and with the onRetainNonConfigurationInstance method I would save and load Fragment state.
Also found another solution which concentrated on the passed data between the Fragments (A,B and passed String data) here.
I hope one of these solutions are suitable for you!
Just call setOffscreenPageLimit() in onCreate() (after initializing ViewPager). The OffscreenPageLimit sets the number of pages that should be retained to either side of the current page. Set the minimum number of fragments you want to initiate either side.

Categories

Resources