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 !
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
Basically i have BottomNavigationView activity in that there are 3 fragments (tab1,tab2,tab3) which contain 3 webviews, what i actually wanna to do is while scrolling down the webview my actionbar should hide, likegetSupportActionBar().hide(); i know already there are answers in the stack overflow for the same question, but i don't know what to do in my case, because i am a beginner in android development
here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hackerinside.jaisonjoseph.polysocial.MainActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#android:color/holo_blue_dark">
<TextView
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
/>
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
android:layout_alignParentBottom="true"
app:menu="#menu/navigation" />
This is my first fragment (fragment_tab1)
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.hackerinside.jaisonjoseph.polysocial.tab1">
<FrameLayout
android:id="#+id/frame1"
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#android:color/transparent">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="3dp"
android:background="#android:color/transparent"
android:foregroundGravity="top"
android:progressDrawable="#drawable/custom_progress"
android:progress="20"/>
</FrameLayout>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</WebView>
This is my java code for tab1
package com.hackerinside.jaisonjoseph.polysocial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
/**
* A simple {#link Fragment} subclass.
*/
public class tab1 extends Fragment {
public ProgressBar bar;
public FrameLayout frameLayout;
public tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab1, null);
frameLayout=(FrameLayout) rootView.findViewById(R.id.frame1);
bar=(ProgressBar)rootView.findViewById(R.id.progressBar1);
bar.setMax(100);
final WebView view=(WebView) rootView.findViewById(R.id.webview);
view.loadUrl("http://facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
view.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view1,int progress){
frameLayout.setVisibility(View.VISIBLE);
bar.setProgress(progress);
if (progress==100){
frameLayout.setVisibility(View.GONE);
}
super.onProgressChanged(view1,progress);
}
});
view.getSettings().setBuiltInZoomControls(true);
view.getSettings().setDisplayZoomControls(false);
bar.setProgress(0);
return rootView;
}
}
Here is a sample idea of implementation.
boolean isShowing;
//oncraete code is here
WebView mScrollView = (WebView) findViewById(R.id.scrollView);
mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
float mfloat = mScrollView.getScrollY();
if (mfloat >= tToolbar.getHeight() && isShowing) {
toolbarAnimateHide();
} else if (mfloat == 0 && !isShowing) {
toolbarAnimateShow(0);
}
}
});
private void toolbarAnimateShow(final int verticalOffset) {
isShowing = true;
//tToolbar is your view(any view)
// add getSupportActionBar().hide() this code here to hide actionbar
// remove below code or comment
tToolbar.animate()
.translationY(0)
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
toolbarSetElevation(verticalOffset == 0 ? 0 : TOOLBAR_ELEVATION);
}
});
}
private void toolbarAnimateHide() {
isShowing = false;
// add getSupportActionBar().show() this code here to showactionbar
// remove below code or comment
//tToolbar is your view(any view)
tToolbar.animate()
.translationY(-tToolbar.getHeight())
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
toolbarSetElevation(0);
}
});
}
Ads(smart banner admob) recently disappeared in my application although they just worked fine before.
The following message shows when running the app in Eclipse with a virtual device:
on Failed To Receive Ad(Invalid Ad request.)
When I open my main.xml file this error message is shown:
Unexpected namespace prefix "xmlns" found for tag LinearLayout
Files:
main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fullwrapper"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#5a4872" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="#5a4872" >
<LinearLayout
android:id="#+id/splash"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/splashscreen"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<Button
android:id="#+id/button_play"
android:background="#drawable/btn_gameplay"
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center_horizontal|center_vertical"
android:orientation="horizontal"
android:text="#string/button_play"
android:textColor="#ffffff"
android:textStyle="bold"
android:textSize="25.0sp" />
<ImageView
android:id="#+id/image_splash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/appname"
android:gravity="center_horizontal" />
</LinearLayout>
<view
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="maazbah.memory.game.kids.ui.MemoryGridView"
android:gravity="center"
android:horizontalSpacing="8dp"
android:layoutAnimation="#anim/layout_random_fade"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="8dp"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center" >
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="#string/banner_ad_unit_id"
ads:adSize="BANNER"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
ads:loadAdOnCreate="true"
/>
</LinearLayout>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="auto"
package="maazbah.memory.game.kids">
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:logo="#drawable/logo"
android:hardwareAccelerated="true">
<activity android:name="maazbah.memory.game.kids.ui.MainActivity"
android:screenOrientation="portrait"
android:label="#string/activity_title" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="maazbah.memory.game.kids.ui.PreferencesActivity"
android:screenOrientation="portrait"
android:label="#string/activity_title" >
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
MainActivity.java
package maazbah.memory.game.kids.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import maazbah.memory.game.kids.Constants;
import maazbah.memory.game.kids.PreferencesService;
import maazbah.memory.game.kids.R;
import maazbah.memory.game.kids.Rotate3dAnimation;
import org.androidsoft.utils.sound.SoundManager;
/**
* AbstractMainActivity
*/
public abstract class AbstractMainActivity extends Activity implements OnClickListener
{
private static final String PREF_STARTED = "started";
private static final int SOUND_NEW_GAME = 1000;
private static final int SPLASH_SCREEN_ROTATION_COUNT = 2;
private static final int SPLASH_SCREEN_ROTATION_DURATION = 2000;
private static final int GAME_SCREEN_ROTATION_COUNT = 2;
private static final int GAME_SCREEN_ROTATION_DURATION = 2000;
private static final String KEY_VERSION = "version";
private static final int DEFAULT_VERSION = 1; // should be set to 0 after 1.4
protected boolean mQuit;
private ViewGroup mContainer;
private View mSplash;
private Button mButtonPlay;
private boolean mStarted;
protected abstract View getGameView();
protected abstract void newGame();
protected abstract void preferences();
/**
* {#inheritDoc }
*/
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
SoundManager.init(AbstractMainActivity.this);
setContentView(R.layout.main);
mContainer = (ViewGroup) findViewById(R.id.container);
mSplash = (View) findViewById(R.id.splash);
mButtonPlay = (Button) findViewById(R.id.button_play);
mButtonPlay.setOnClickListener(this);
checkLastVersion();
}
/**
* {#inheritDoc }
*/
#Override
protected void onResume()
{
super.onResume();
SharedPreferences prefs = getPreferences(0);
mStarted = prefs.getBoolean(PREF_STARTED, false);
if (mStarted)
{
mSplash.setVisibility(View.GONE);
getGameView().setVisibility(View.VISIBLE);
} else
{
mSplash.setVisibility(View.VISIBLE);
getGameView().setVisibility(View.GONE);
}
if (!SoundManager.isInitialized())
{
SoundManager.init(this);
}
SoundManager.instance().addSound(SOUND_NEW_GAME, R.raw.start_game);
}
/**
* {#inheritDoc }
*/
#Override
protected void onPause()
{
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
if (!mQuit)
{
editor.putBoolean(PREF_STARTED, mStarted);
} else
{
editor.remove(PREF_STARTED);
}
editor.commit();
SoundManager.release();
}
/**
* {#inheritDoc }
*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
/**
* {#inheritDoc }
*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_new:
onNewGame();
return true;
case R.id.menu_quit:
quit();
return true;
case R.id.menu_preferences:
preferences();
return true;
}
return false;
}
private void onNewGame()
{
if( PreferencesService.instance().isSoundEnabled() )
{
SoundManager.instance().playSound(SOUND_NEW_GAME);
}
newGame();
}
/**
* Quit the application
*/
void quit()
{
mQuit = true;
AbstractMainActivity.this.finish();
}
/**
* {#inheritDoc }
*/
public void onClick(View v)
{
if (v == mButtonPlay)
{
applyRotation(0, SPLASH_SCREEN_ROTATION_COUNT * 360);
}
}
protected void showEndDialog(String title, String message, int icon)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setIcon(icon);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton(getString(R.string.new_game),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
onNewGame();
}
});
builder.setNegativeButton(getString(R.string.quit),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
quit();
}
});
AlertDialog alert = builder.create();
alert.show();
}
// 3D anim from Splash Screen to Game screen
/**
* Setup a new 3D rotation on the container view.
*
* #param start the start angle at which the rotation must begin
* #param end the end angle of the rotation
*/
private void applyRotation(float start, float end)
{
// Find the center of the container
final float centerX = mContainer.getWidth() / 2.0f;
final float centerY = mContainer.getHeight() / 2.0f;
// Create a new 3D rotation with the supplied parameter
// The animation listener is used to trigger the next animation
final Rotate3dAnimation rotation =
new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
rotation.setDuration(SPLASH_SCREEN_ROTATION_DURATION);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView());
mContainer.startAnimation(rotation);
}
/**
* This class listens for the end of the first half of the animation.
* It then posts a new action that effectively swaps the views when the container
* is rotated 90 degrees and thus invisible.
*/
private final class DisplayNextView implements Animation.AnimationListener
{
private DisplayNextView()
{
}
public void onAnimationStart(Animation animation)
{
if( PreferencesService.instance().isSoundEnabled() )
{
SoundManager.instance().playSound(SOUND_NEW_GAME);
}
}
public void onAnimationEnd(Animation animation)
{
mContainer.post(new SwapViews());
}
public void onAnimationRepeat(Animation animation)
{
}
}
/**
* This class is responsible for swapping the views and start the second
* half of the animation.
*/
private final class SwapViews implements Runnable
{
public void run()
{
final float centerX = mContainer.getWidth() / 2.0f;
final float centerY = mContainer.getHeight() / 2.0f;
Rotate3dAnimation rotation;
mSplash.setVisibility(View.GONE);
getGameView().setVisibility(View.VISIBLE);
getGameView().requestFocus();
rotation = new Rotate3dAnimation(0, 360 * GAME_SCREEN_ROTATION_COUNT, centerX, centerY, 310.0f, false);
rotation.setDuration(GAME_SCREEN_ROTATION_DURATION);
rotation.setFillAfter(true);
rotation.setInterpolator(new DecelerateInterpolator());
mContainer.startAnimation(rotation);
mStarted = true;
}
}
private void checkLastVersion()
{
int resTitle;
int resMessage;
final int lastVersion = getVersion();
if (lastVersion < Constants.VERSION)
{
if (lastVersion == 0)
{
// This is a new install
resTitle = R.string.first_run_dialog_title;
resMessage = R.string.first_run_dialog_message;
} else
{
// This is an upgrade.
resTitle = R.string.whats_new_dialog_title;
resMessage = R.string.whats_new_dialog_message;
}
// show what's new message
saveVersion(Constants.VERSION);
showWhatsNewDialog(resTitle, resMessage, R.drawable.icon);
}
}
private int getVersion()
{
SharedPreferences prefs = getSharedPreferences(AbstractMainActivity.class.getName(), Activity.MODE_PRIVATE);
return prefs.getInt(KEY_VERSION, DEFAULT_VERSION);
}
private void saveVersion(int version)
{
SharedPreferences prefs = getSharedPreferences(AbstractMainActivity.class.getName(), Activity.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt(KEY_VERSION, version);
editor.commit();
}
protected void showWhatsNewDialog(int title, int message, int icon)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setIcon(icon);
builder.setMessage(message);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
onNewGame();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Does anyone know what is wrong with my code?
Thanks.
Remove
xmlns:android="http://schemas.android.com/apk/res/android"from nested LinearLayout. Keep it only in root LinearLayout (first one). Because Android namespace in Android.xml files should be declared just once.
Change your ads namespace in LinearLayout to
xmlns:ads="http://schemas.android.com/apk/res-auto"
Thanks for Rebly dear Shubham Shukla & Yupi,
I have deleted this line from nested linearlayout.
xmlns:android="http://schemas.android.com/apk/res/android"
and keep it only in root linearlayout,
and i move this line to root linearlayout.
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
The file (main.xml) It has become :
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/fullwrapper"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#5a4872" >
<LinearLayout
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="#5a4872" >
<LinearLayout
android:id="#+id/splash"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/splashscreen"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<Button
android:id="#+id/button_play"
android:background="#drawable/btn_gameplay"
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center_horizontal|center_vertical"
android:orientation="horizontal"
android:text="#string/button_play"
android:textColor="#ffffff"
android:textStyle="bold"
android:textSize="25.0sp" />
<ImageView
android:id="#+id/image_splash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/appname"
android:gravity="center_horizontal" />
</LinearLayout>
<view
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="maazbah.memory.game.kids.ui.MemoryGridView"
android:gravity="center"
android:horizontalSpacing="8dp"
android:layoutAnimation="#anim/layout_random_fade"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="8dp"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center" >
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="ca-app-pub-9321782199225340/4561186116"
ads:adSize="BANNER"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
ads:loadAdOnCreate="true"
/>
</LinearLayout>
</LinearLayout>
and new message shown in eclips after this amendment,
To get test ads on this device, call adRequest.addTestDevice("DDE8F001C78F8B58CE003B1327202313");
and the admob banner dosent shown until now after this amendment !
I have used the following code to create a swipe view. This is my java code
package com.lorentzos.swipecards;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class MyActivity extends Activity {
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
FrameLayout.LayoutParams params;
View v;
#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
/*frameLayout=(FrameLayout)v.findViewById(R.id.frame_layout);*/
v=findViewById(R.id.frame_layout);
ButterKnife.inject(this);
/*al.add("c");
al.add("python");
al.add("java");
al.add("html");
al.add("c++");
al.add("css");
al.add("javascript");*/
int height=500;
int width=500;
params = new FrameLayout.LayoutParams(width, height);
/*params.gravity= Gravity.CENTER;*/
al = new ArrayList<>();
for(int i=0; i<=7; i++) {
al.add("php");
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al);
flingContainer.setMaxVisible(4);
/*v.setLayoutParams(params);*/
flingContainer.setAdapter(arrayAdapter);
height=height-20;
}
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(MyActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(MyActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
/*al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;*/
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(MyActivity.this, "Clicked!");
}
});
}
static void makeToast(Context ctx, String s){
Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
}
Below are the xml files
activity_my.xml
<merge
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"
>
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:id="#+id/frame"
android:background="#ffeee9e2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rotation_degrees="15.5"
app:min_adapter_stack="6"
tools:context=".MyActivity" />
<include layout="#layout/buttons" />
</merge>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp">
<TextView
android:id="#+id/helloText"
android:textSize="40sp"
android:textColor="#android:color/white"
android:background="#A5F"
android:gravity="center"
tools:text="#string/hello_world"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="#+id/item_swipe_left_indicator"
android:alpha="0"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_margin="10dp"
android:background="#A5F" />
<View
android:id="#+id/item_swipe_right_indicator"
android:alpha="0"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_margin="10dp"
android:layout_gravity="right"
android:background="#5AF" />
</FrameLayout>
buttons.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/left"
android:layout_margin="10dp"
android:text="Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/right"
android:layout_margin="10dp"
android:text="Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Refer the attached screenshots.
[![enter image description here][2]][2]
But i want the images to come like a stack.. Not exactly overlapped. Refer this
Can anyone help me achieve this?
This is a link with your solution https://github.com/Diolor/Swipecards
Incase you use custom ArrayAdaper on inflating layout this is the code that worked for me
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.swipe_item, parent, false);
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.