admob stopped working [ on Failed To Receive Ad(Invalid Ad request.) ] - android

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 !

Related

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 !

Android: ViewPager gets stuck in between views

I have a ViewPager which swipes between Fragments. I'm using a FragmentStatePagerAdapter to feed the Fragments to the ViewPager. If the user swipes left at a normal pace, and then swipes right very quickly, they can get the ViewPager into a weird state where it shows multiple Fragments.
For example, if the user is on Fragment A, then swipes left to Fragment B at a normal pace, and then quickly swipes right to go back to Fragment A, then on screen shows both Fragments A & B.
Anybody have any ideas on why this is happening or a good way to prevent it?
Here's what it looks like:
Here's my ViewPager definition in XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.company.views.CustomActionBar
android:id="#+id/customActionBar"
android:layout_width="match_parent"
android:layout_height="#dimen/height_actionbar"
android:layout_alignParentTop="true"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/customActionBar"/>
Also, I logged output from my onPageChangeListener() and noticed that when the ViewPager gets stuck in between views, it's reporting a positionOffset of 0. Here's what the ViewPager's values look like as it transitions from STATE_DRAGGING to STATE_SETTLING to STATE_IDLE when it lands in this weird state:
state = 0 prevState: 2 position: 1 positionOffset: 0.0
state = 1 prevState: 0 position: 1 positionOffset: 0.0
state = 2 prevState: 1 position: 1 positionOffset: 0.4069444
state = 0 prevState: 2 position: 2 positionOffset: 0.0
So it appears as if the ViewPager is reporting the wrong positionOffset back to me.
Full sample code Activity and Adapter:
public class ActivityBagelProfileViewer extends CustomAbstractFragmentActivity
implements CustomActionBarContract, ListenerProgress, ListenerSync
{
public static final String EXTRA_BAGEL_INDEX = "BAGEL";
public static final int REQUEST_CODE_BAGEL_PROFILE_VIEWER = 4000;
public static final int RESULT_GO_TO_PASS_FLOW = 12;
public static final int RESULT_GO_TO_LIKE_FLOW = 14;
public static final int RESULT_GO_TO_SEE_MORE_BAGELS = 16;
private ViewPager mProfilesViewPager;
private CustomActionBar mCustomActionBar;
private int mViewPagerPosition;
private DialogProgress mDialogProgress;
private BagelViewPagerAdapter mAdapterBagelViewPager;
private List<Bagel> mListBagels;
#Override
protected void onCreate(Bundle savedInstanceState)
{
Logger.d("ENTER");
super.onCreate(savedInstanceState);
if (ManagerGive.IS_BRANCH_SESSION_OPEN == false)
{
ManagerGive.initializeBranchMetricsSession();
}
setContentView(R.layout.activity_with_viewpager);
mCustomActionBar = (CustomActionBar) findViewById(R.id.customActionBar);
mCustomActionBar.setMenu(this);
mProfilesViewPager = (ViewPager) findViewById(R.id.viewPager);
if (getIntent().getExtras() != null)
{
mViewPagerPosition = getIntent().getExtras().getInt(EXTRA_BAGEL_INDEX, 0);
}
}
#Override
protected void onStop()
{
super.onStop();
ManagerGive.closeBranchMetricsSession();
}
public void onIconClick(View view)
{
Logger.d("ENTER");
finishWithAnimation();
}
private void finishWithAnimation()
{
setResult(RESULT_OK);
finish();
overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
}
#Override
public void onBackPressed()
{
if (!super.handleBackPressedEvent())
{
finishWithAnimation();
}
}
private void setupNewAdapter()
{
mListBagels = Bakery.getInstance().getManagerBagel().getCopyOfBagelsWithoutCurrent();
mAdapterBagelViewPager = new BagelViewPagerAdapter(getSupportFragmentManager(), mListBagels, this);
mProfilesViewPager.setAdapter(mAdapterBagelViewPager);
mProfilesViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
setActionBar(position);
mViewPagerPosition = position;
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
mProfilesViewPager.setCurrentItem(mViewPagerPosition, false);
}
#Override
protected void onResume()
{
Logger.d("ENTER");
super.onResume();
Bakery.getInstance().getManagerSyncData().addListener(this);
if (mProfilesViewPager.getAdapter() == null)
{
Logger.d("Adapter null. Setting new adapter");
setupNewAdapter();
}
else
{
if (mProfilesViewPager.getAdapter().getCount() !=
Bakery.getInstance().getManagerBagel().getCopyOfBagelsWithoutCurrent().size())
{
Logger.d("Bagel list in Bakery changed size. Setting new adapter");
setupNewAdapter();
}
}
if (mListBagels.size() > 0)
{
setActionBar(mViewPagerPosition);
mDialogProgress = new DialogProgress(this);
}
else
{
//kv Something has gone terribly wrong if we don't have any Bagels, just finish
finish();
}
}
private void setActionBar(int bagelIndex)
{
Logger.d("bagelIndex=" + bagelIndex);
Bagel bagel = mListBagels.get(bagelIndex);
//kv If this is our current bagel and we haven't taken action yet, then show timer
if (Bakery.getInstance().getManagerBagel().getCurrentBagel() == bagel
&& bagel.getAction() != Bagel.ACTION_LIKED && bagel.getAction() != Bagel.ACTION_PASSED)
{
Logger.d("Setting up #timer in action bar");
mCustomActionBar.startTimeLeftTimer(DateUtils.getMillisFromUtc(bagel.getEndDate()),
this, new ListenerTimer()
{
#Override
public void onTimerExpired()
{
Logger.d("ENTER");
Bakery.getInstance().getManagerSyncData().performSync(null, false);
}
}, mCustomActionBar.getTextViewTimeLeft(), R.string.timer_blank);
mCustomActionBar.setLabel(R.string.time_left);
mCustomActionBar.hideTitle();
}
//kv Otherwise show date
else
{
mCustomActionBar.setTitle(DateUtils.getLocalizedDateFromStringDate(bagel.getStartDate(), DateUtils.DATE_WITH_TIME_PATTERN));
mCustomActionBar.stopTimeLeftTimer();
mCustomActionBar.hideTimeLeft();
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_BAGEL_INDEX, mViewPagerPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
Logger.d("ENTER");
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey(EXTRA_BAGEL_INDEX))
{
mViewPagerPosition = savedInstanceState.getInt(EXTRA_BAGEL_INDEX);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Logger.d("requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data);
switch (requestCode)
{
case ActivityBeanShop.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK && data != null)
{
//fp user purchased sufficient beans to resume their transaction
PurchaseType interruptedPurchaseType = (PurchaseType) data.getSerializableExtra(ActivityBeanShop.EXTRA_PURCHASE_TYPE);
switch (interruptedPurchaseType)
{
case BONUS_BAGEL:
case OPEN_SESAME:
case REMATCH:
Bundle bundle = new Bundle();
bundle.putSerializable(ManagerPurchase.EXTRA_PURCHASE_TYPE, interruptedPurchaseType);
ManagerEvents.notifyListeners(EventType.BEAN_TRANSACTION_FOR_FEATURE_UNLOCK_COMPLETE, bundle);
Logger.d("Notified listeners about #purchase bean transaction, can now resume feature #purchase");
break;
default:
Logger.w("Unrecognized purchase type: " + interruptedPurchaseType.getItemName());
}
}
break;
default:
Logger.w("Could not recognize code: " + requestCode);
}
}
#Override
public int getTitleId()
{
return R.string.bagel_action_checked;
}
#Override
public int getIconId()
{
return R.drawable.selector_icon_up;
}
#Override
public void showProgress(int stringId)
{
mDialogProgress.setText(stringId);
mDialogProgress.show();
}
#Override
public void dismissProgress()
{
ViewUtils.safelyDismissDialog(mDialogProgress);
}
public void setActionBar()
{
setActionBar(mViewPagerPosition);
}
#Override
public void onSyncComplete()
{
Logger.d("ENTER");
mListBagels = Bakery.getInstance().getManagerBagel().getCopyOfBagelsWithoutCurrent();
mAdapterBagelViewPager.setBagels(mListBagels);
}
public boolean isShowingThisBagel(Bagel bagel)
{
Bagel currentlyShownBagel = mListBagels.get(mViewPagerPosition);
return bagel == currentlyShownBagel;
}
private static class BagelViewPagerAdapter extends FragmentStatePagerAdapter
{
private List<Bagel> mBagels;
private ListenerProgress mListenerProgress;
public BagelViewPagerAdapter(FragmentManager fragmentManager, List<Bagel> bagels,
ListenerProgress listenerProgress)
{
super(fragmentManager);
Logger.d("bagels=" + bagels);
this.mBagels = bagels;
mListenerProgress = listenerProgress;
}
#Override
public Fragment getItem(int i)
{
Logger.d("i=" + i);
UserProfile myProfile = Bakery.getInstance().getManagerUserProfile().getMyOwnProfile();
FragmentProfile fragment = FragmentProfile.newInstance(mBagels.get(i), false, myProfile);
fragment.setListenerProgress(mListenerProgress);
return fragment;
}
#Override
public int getCount()
{
return mBagels.size();
}
public void setBagels(List<Bagel> bagels)
{
mBagels = bagels;
notifyDataSetChanged();
}
}
}
And here's the XML layout code for the layout of each Fragment (had to cut some out b/c of SO char limit):
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-0.5dp"
android:orientation="vertical"
android:animateLayoutChanges="true"
android:id="#+id/profile_top_container">
<!-- Photos section with pager/carousel -->
<FrameLayout
android:id="#+id/photoViewpagerContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.coffeemeetsbagel.views.CustomAsShitViewPager
android:id="#+id/pager_profile_images"
xmlns:android="http://schemas.android.com/apk/res/android"
app:aspectRatio="#integer/photo_ratio_height_over_width"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="#+id/linearLayout_bulletsAndFriendsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom">
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/textView_stamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
app:customFont="Raleway-Bold.ttf"
android:layout_gravity="end"
android:textSize="#dimen/text_stamp"
android:paddingTop="#dimen/margin_large"
android:layout_marginEnd="#dimen/margin_xxxxxsmall"
android:layout_marginRight="#dimen/profile_margin_smaller"/>
<!-- photo circle indicators -->
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/bullet_indicators"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/circle_indicator_margin_bottom"
android:clickable="false"
app:fillColor="#color/blue_cmb"
app:pageColor="#color/gray_background"
app:radius="#dimen/circle_indicator_radius"
app:strokeWidth="0dp"/>
<!-- container for mutual friends strip -->
<RelativeLayout
android:id="#+id/relativeLayout_mutual_friends_container"
android:layout_width="match_parent"
android:layout_height="#dimen/baseline_grid_component_touchable"
android:background="#color/white_transparent"
android:visibility="gone">
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/textView_mutual_friends_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
style="#style/profile_mutual_friends_text"/>
<LinearLayout
android:id="#+id/linearLayout_mutual_friends_icons"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="#dimen/baseline_grid_small"
android:layout_marginRight="#dimen/baseline_grid_small"
android:layout_centerVertical="true">
<ImageView
android:id="#+id/imageView_icon0"
android:layout_width="#dimen/baseline_grid_component_touchable"
android:layout_height="#dimen/baseline_grid_component_touchable"
android:padding="#dimen/typography_smallest"
android:background="#color/transparent"
android:visibility="gone"/>
<ImageView
android:id="#+id/imageView_icon1"
android:layout_width="#dimen/baseline_grid_component_touchable"
android:layout_height="#dimen/baseline_grid_component_touchable"
android:background="#color/transparent"
android:padding="#dimen/typography_smallest"
android:visibility="gone"/>
<ImageView
android:id="#+id/imageView_icon2"
android:layout_width="#dimen/baseline_grid_component_touchable"
android:layout_height="#dimen/baseline_grid_component_touchable"
android:background="#color/transparent"
android:padding="#dimen/typography_smallest"
android:visibility="gone"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</FrameLayout>
<!-- Buttons section with User Actions for pass / like-->
<LinearLayout
android:id="#+id/linearLayout_buttons_pass_like"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/baseline_grid_smaller"
android:layout_marginLeft="#dimen/baseline_grid_small"
android:layout_marginRight="#dimen/baseline_grid_small"
android:layout_marginTop="#dimen/baseline_grid_medium"
android:orientation="horizontal"
android:visibility="gone">
<ImageView
android:id="#+id/button_pass"
android:layout_width="0dp"
android:layout_height="#dimen/profile_action_button_height"
android:layout_weight="1"
android:background="#drawable/ripple_button_pass"
android:clickable="true"
android:src="#drawable/icon_pass_pressed"
android:scaleType="center"
android:layout_marginRight="#dimen/margin_small"/>
<ImageView
android:id="#+id/button_like"
android:layout_width="0dp"
android:layout_height="#dimen/profile_action_button_height"
android:layout_weight="1"
android:background="#drawable/ripple_button_like"
android:clickable="true"
android:src="#drawable/icon_like_pressed"
android:scaleType="center"
android:layout_marginLeft="#dimen/margin_small"/>
</LinearLayout>
<!-- Buttons section with User Actions for rematch / give-->
<LinearLayout
android:id="#+id/linearLayout_buttons_rematch_give"
android:layout_width="match_parent"
android:layout_height="#dimen/give_ten_button_height"
android:layout_marginBottom="#dimen/baseline_grid_smaller"
android:layout_marginLeft="#dimen/baseline_grid_small"
android:layout_marginRight="#dimen/baseline_grid_small"
android:layout_marginTop="#dimen/baseline_grid_medium"
android:orientation="horizontal"
android:gravity="center"
android:visibility="gone">
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/textView_rematch"
android:layout_width="#dimen/zero_dip"
android:layout_height="match_parent"
android:layout_marginRight="#dimen/give_take_button_margin_side"
android:layout_weight="1"
style="#style/button_give_take_rematch"
android:text="#string/rematch"/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/text_view_give_with_rematch"
android:layout_width="#dimen/zero_dip"
android:layout_weight="1"
android:layout_height="match_parent"
style="#style/button_give_take_rematch"
android:text="#string/give"/>
</LinearLayout>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/textView_they_like_you"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/icon_like_alert"
android:drawablePadding="#dimen/margin_xxsmall"
style="#style/profile_info_item_value"
android:layout_marginLeft="#dimen/margin_med"
android:paddingTop="#dimen/baseline_grid_smaller"/>
<ViewStub
android:id="#+id/viewStub_profile_feedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="#layout/profile_feedback"/>
<!-- Profile information table -->
<!-- Name -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:paddingTop="#dimen/baseline_grid_smaller"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/profile_info_label_name"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_name"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Age -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/profile_info_label_age"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_age"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Location -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/location"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_location"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Ethnicity -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/profile_info_label_ethnicity"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_ethnicity"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Height -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/profile_info_label_height"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_height"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Religion -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/profile_info_label_religion"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_religion"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Occupation -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
<com.coffeemeetsbagel.views.CustomTextView
android:text="#string/profile_info_label_occupation"
style="#style/profile_info_item_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<com.coffeemeetsbagel.views.CustomTextView
android:id="#+id/profile_info_value_occupation"
style="#style/profile_info_item_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<!-- Employer -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/profile_info_item_layout_margins"
android:orientation="horizontal">
...
I've noticed that I see this issue if I have some animations given by the animateLayoutChanges. Just deactivating it in the xml file, prevents the pages to be stuck in the middle.
Try the following sample code and modify it as per your requirement(I guess your are loading the image on main UI thread and not caching it, its just a guess). In this code i am downloading and caching the images from the internet :
Create a Activity class named SomeFragTest
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.LruCache;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.ImageView;
public class SomeFragTest extends FragmentActivity{
private LruCache<String, Bitmap> cache;
private List<String> strings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
ViewPager mViewPager = (ViewPager)findViewById(R.id.viewPager);
strings=new ArrayList<String>();
setData();
int memClass = ( ( ActivityManager )getSystemService( Context.ACTIVITY_SERVICE ) ).getMemoryClass();
int cacheSize = 1024 * 1024 * memClass / 8;
cache=new LruCache<String, Bitmap>(cacheSize){
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount()/1024;
}
};
mViewPager.setOffscreenPageLimit(strings.size());
mViewPager.setAdapter(new MyPageAdapter(getSupportFragmentManager()));
}
private void setData()
{
for (int i = 1; i <= 10; i++) {
strings.add("http://dummyimage.com/600x400/000/0011ff.png&text="+i);
}
}
public void loadBitmap(int position , ImageView imageView) {
imageView.setImageResource(R.drawable.ic_launcher);
imageView.setTag(strings.get(position));
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(strings.get(position));
}
class MyPageAdapter extends FragmentPagerAdapter
{
public MyPageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment=new ChildFrag();
Bundle bundle=new Bundle();
bundle.putInt("POS", arg0);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return strings.size();
}
}
class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
public String url;
private final WeakReference<ImageView> imageViewReference;
public BitmapDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
url=params[0];
if(cache.get(url)!=null){
Log.e("FROM ", "CACHE");
return cache.get(url);
}
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String url) {
Log.e("FROM ", "URL");
HttpClient client=new DefaultHttpClient();
//final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
//final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return decodeBitmapWithGiveSizeFromResource(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
Log.e("ERROR", " " +e.getLocalizedMessage());
} finally {
if (client != null) {
//client.close();
}
}
return null;
}
/***************/
private void copy(InputStream inputStream,ByteArrayOutputStream arrayOutputStream)
{
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) > -1 ) {
arrayOutputStream.write(buffer, 0, len);
}
arrayOutputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Bitmap decodeBitmapWithGiveSizeFromResource(InputStream inputStream) {
//BufferedInputStream bufferedInputStream=new BufferedInputStream(inputStream);
final BitmapFactory.Options options = new BitmapFactory.Options();
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(inputStream,out);
InputStream in2 = new ByteArrayInputStream(out.toByteArray());
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap=BitmapFactory.decodeStream(in2,null, options);
try {
inputStream.close();
in2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return scaleDown(bitmap,false);
}
private Bitmap scaleDown(Bitmap realImage, boolean filter) {
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, 100,
100, filter);
Bitmap output = Bitmap.createBitmap(newBitmap.getWidth(), newBitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, newBitmap.getWidth(), newBitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 10;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(newBitmap, rect, rect, paint);
return output;
}
private int calculateInSampleSize(BitmapFactory.Options options) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > 100 || width > 100) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >100
&& (halfWidth / inSampleSize) >100) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
cache.put(url, bitmap);
ImageView imageView = imageViewReference.get();
// BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
// Change bitmap only if this process is still associated with it
if (((String)imageView.getTag()).equalsIgnoreCase(url)) {
imageView.setImageBitmap(bitmap);
}
}
}
}
}
After this create the xml for it, named activity_layout
<?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" >
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Now we have create the Fragment class that we want to inflate in the ViewPager:
Create a class named ChildFrag as follows
import android.os.Bundle;
import android.support.annotation.Nullable;
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.TextView;
public class ChildFrag extends Fragment {
private int index;
private ImageView imageView;
#Override
#Nullable
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragtest, container, false);
index = getArguments().getInt("POS");
((TextView) view.findViewById(R.id.textView1)).setText("" + index);
imageView = (ImageView) view.findViewById(R.id.imageView1);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((SomeFragTest) getActivity()).loadBitmap(index, imageView);
}
}
Now we have create the xml for the fragment as fragtest:
<?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="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Add the following permission in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
In my case, the problem was an empty Fragment. After create a fragment with a layout, it's starts working as expected.
Basically, I used a empty fragment for test the view:
fragment = new Fragment(); //Strange behavior in ViewPager
When I used the final fragment which has a layout, the behavior was the correct:
fragment = MyFragment.newInstance(); //Correct behavior
I know that this response doesn't answer the current question, but some people with similar problems arrive here. So, I hope it's helpful.
For now, I am thinking there is an issue with the width of the layout. So far I only see one suspect, there is an unknown attribute
app:aspectRatio="#integer/photo_ratio_height_over_width"
in UI element <com.coffeemeetsbagel.views.CustomAsShitViewPager...
Apparently there is a custom attribute in library/code CustomAsShitViewPager, perhaps post the code related to aspectRatio, at least.
I just realized that you're doing a lot of UI work in onCreate() in the main Activity. It is more proper to do the work in onCreateView(). I believe the Android framework is not finish doing the UI work in onCreate() and therefore you see incomplete UI rendering.
I know this is not clearly stated in Android documentation. If you check other SO posts or sample projects, other developers do little UI work in onCreate(). At least, the layouts are simpler than yours.
Here is my suggestion.
Inflate the fragtest layout in an Activity or Fragment in method onCreateView(), using the ID listed on post. Notice the override method only inflates.
Sample code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragtest, container, false);
}
On a Fragment, start accessing the UI elements and the ViewPager, using the ID listed on post. Sample code:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mProfilesViewPager = (ViewPager) findViewById(R.id.viewPager);
...
Extremely late reply, but if someone is having trouble, this is what worked for me.
I was wrapping the ViewPager inside View with custom styling like this:
<View style={{bla bla bla style here}}>
<ViewPager>
<Layout></Layout>
<Layout></Layout>
</ViewPager>
</View>
I just removed <View> from the file and ViewPager fixed itself.
<ViewPager>
<Layout></Layout>
<Layout></Layout>
</ViewPager>
so what I am saying is, try removing some other parent layout tags, maybe they are causing this problem.
PS: this worked in react-native but I hope it helps in other realms as well.
I also encountered this problem, my solution below:
mainViewPager.post { mainViewPager.setCurrentItem(item, false) }
Disabling animations and setting the ViewPager's position manually didn't work for me. In my situation, the bug happened sometimes when navigating to another screen and going back. What I ended up doing was saving the horizontal offset, via a OnPageChangeListener, and "resetting" it to zero in the activity's onResume() if it wasn't zero.
private var lastOffset = 0.0F
override fun onCreate() {
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
lastOffset = positionOffset
}
// other listener methods
}
)
}
override fun onResume() {
if (lastOffset != 0.0F) {
viewPager.beginFakeDrag()
viewPager.fakeDragBy(lastOffset)
viewPager.endFakeDrag()
}
}
For now, I suspect two methods.
1) In the fragment code:
#Override
public int getCount()
{
return mBagels.size();
}
Note: getCount() should return the number of fragments instead of the size of the list. I could not tell how many of fragments you will have. Perhaps you have to keep track in the Adapter.
2) Another, I suspect getItem() method and the use of newInstance(). The related specific code:
FragmentProfile fragment = FragmentProfile.newInstance(mBagels.get(i),...
Notes:
According to Google webpage FragmentStatePagerAdapter, method newInstance should create a new fragment probably because that's when the FragmentStatePagerAdapter does not have the fragment in memory yet OR was released from memory.
Perhaps post the code related to FragmentProfile.newInstance especially if you disagree with my statement above.

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, activity remembering counting data

Is there any way to activity remebers the counting, because when you start the app, you click the button which random generates an image from drawable, and it doesn't let user to press that button for 30 secs.. the problem now is that when you are waiting for counter go to 0 you can easily press option menu, click settings and click "povratak" ,which starts activity all over again and the counter losses its point because user can now again press button that generates image (and I dont want that):/
MainActivity
package com.example.ams;
import java.util.Random;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
final Random rnd = new Random();
ImageView img = null;
Button btnRandom = null;
#Override
protected void onCreate(
final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imgRandom);
btnRandom = (Button) findViewById(R.id.btnRandom);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
public void clickHandler(final View v)
{
switch(v.getId())
{
case R.id.btnRandom:
{
if (!btnRandom.isEnabled())
{
return;
}
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(45);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
btnRandom.setEnabled(false);
new CountDownTimer(30000, 1000) // Wait 30 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
btnRandom.setText("Pričekaj do sljedeće kartice: " + (millisUntilFinished / 1000));
}
#Override
public final void onFinish()
{
btnRandom.setText("PROMIJENI KARTICU !");
btnRandom.setEnabled(true);
}
}.start();
break;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
setContentView(R.layout.help);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void goBack(View v){
startActivity(new Intent(this, MainActivity.class));
}
#Override
public void onBackPressed() {
}
}
activity_main.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=".MainActivity"
android:background="#drawable/bgi"
>
<ImageView
android:id="#+id/imgRandom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
/>
<Button
android:id="#+id/btnRandom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imgRandom"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/imgRandom"
android:onClick="clickHandler"
android:text=" Promijeni karticu !"
android:textColor="#ffffff"
android:textSize="25dp" />
help.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="450dp"
android:fillViewport="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:enabled="true"
android:freezesText="false"
android:overScrollMode="always"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
android:text="UVOD:Uz svaki scenario organizator moze odrediti da se koristi "AMS sustav" zbog realnijeg pristupa igri i viseg stupnja MILSIM-a. Organizator bira medice (ili kako se vec odredi) i oni moraju imati prilikom pocetka igre 46 kartica. />
</ScrollView>
<Button
android:id="#+id/button1"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:text="Povratak" />
And if there is possible , show me your answers in code format, cause english is not my native language and often I don't understand what you guys mean :)
What you can do is inside the onPause() method store the current value of the timer in the SharedPreferences. When your app resumes in onResume(), you can get that value again, and if it exists start from that.

How to fit my design to all devices?

Hi I am developing a app in which alphabets are not fitting for every device. For HCL ME tablet my design won't fit. For samsung it is working. MY XML file is:
<?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:layout_weight="2" android:orientation="vertical">
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_weight="1">
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_weight="1">
<TextView android:id="#+id/letter1" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></TextView>
<TextView android:id="#+id/letter2" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip"></TextView>
<TextView android:id="#+id/letter3" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip"></TextView>
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_weight="1">
<ImageView android:id="#+id/imag"
android:gravity="center"
android:scaleType = "fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_gravity="center">
</ImageView>
</LinearLayout>
</LinearLayout>
<LinearLayout android:layout_gravity="bottom"
android:id="#+id/linearLayout2"
android:layout_height="wrap_content" android:orientation="horizontal" android:layout_width="match_parent">
<Button android:id="#+id/previous" android:layout_width="wrap_content" android:layout_weight="1" android:text="Previous" android:layout_height="wrap_content" ></Button>
<Button android:id="#+id/practice" android:layout_width="wrap_content" android:layout_weight="1" android:text="Practice" android:layout_height="wrap_content" android:onClick="onClick"></Button>
<Button android:id="#+id/home" android:layout_width="wrap_content" android:layout_weight="1" android:text="Home" android:layout_height="wrap_content"></Button>
<Button android:id="#+id/spell" android:layout_width="wrap_content" android:layout_weight="1" android:text="Spell" android:layout_height="wrap_content" android:onClick="Content"></Button>
<Button android:id="#+id/next" android:layout_width="wrap_content" android:layout_weight="1" android:text="Next" android:layout_height="wrap_content" android:onClick="Content"></Button>
</LinearLayout>
</LinearLayout>
and my java file is:
package com.android;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.SimpleGestureFilter.SimpleGestureListener;
public class MyAcivity extends Activity implements SimpleGestureListener {
private SimpleGestureFilter detector;
private static int counter=-1;
private String[] mBtn1 ={"C","D","E","F","G","H","IÄ","J","K","L","M","N","O","CA","CB"};
private TextView txtLetter;
private ImageView imgLetter;
private int[] imgArr={R.drawable.w1,R.drawable.w2,R.drawable.w3,R.drawable.w4,R.drawable.w5,R.drawable.w6,R.drawable.w7,R.drawable.w8,R.drawable.w9,R.drawable.w10,R.drawable.w11,R.drawable.w12,
R.drawable.w13,R.drawable.w14,R.drawable.w15};
private TextView txtKannada;
private String[] mBtn2 = {"CgÀ¸À","DªÉÄ","E°","F±À","GqÀ","Hl","IĶ","J¯É","Kr","LzÀÄ","M¯É","N¯É","OµÀzsÀ",
"CAUÀr","CB"};
private String[] mBtn3 = {"ARASA","AME","ILI","ISA","UDA","UTA","RUSHI","ELE","EDI","AIDU","oLE","OLE","AUSHADA",
"ANGADI","AHA"};
private TextView txtEnglish;
private int[] mAudio = {R.raw.a,R.raw.b,R.raw.c,R.raw.d,R.raw.e,R.raw.f,R.raw.g,R.raw.h,R.raw.i,R.raw.j,
R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o};
protected MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
detector = new SimpleGestureFilter(this,this);
if(counter == -1)
counter =getIntent().getExtras().getInt("POSITION");
Typeface tf = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/brhknd.ttf");
txtLetter = (TextView)findViewById(R.id.letter1);
txtKannada = (TextView)findViewById(R.id.letter2);
txtEnglish = (TextView)findViewById(R.id.letter3);
imgLetter = (ImageView)findViewById(R.id.imag);
txtLetter.setTypeface(tf);
txtLetter.setText(mBtn1[counter]);
txtLetter.setTextSize(350);
txtKannada.setTypeface(tf);
txtKannada.setText(mBtn2[counter]);
txtKannada.setTextSize(100);
txtEnglish.setText(mBtn3[counter]);
txtEnglish.setTextSize(50);
Button btnNext = (Button)findViewById(R.id.next);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(counter<imgArr.length-1)
counter++;
changeContent();
}
});
Button mPlay = (Button)findViewById(R.id.spell);
mPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MySwara.this, mAudio[counter]);
mp.start();
}
});
Button btnPrvs = (Button)findViewById(R.id.previous);
btnPrvs.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(counter>0)
counter--;
changeContent();
}
});
Button btnPractice = (Button)findViewById(R.id.practice);
btnPractice.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MySwara.this,DrawingActivity.class);
startActivity(intent);
}
});
Button btnHome = (Button)findViewById(R.id.home);
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MySwara.this,mainClass.class);
startActivity(intent);
}
});
}
public void changeContent()
{
txtLetter.setText(mBtn1[counter]);
txtKannada.setText(mBtn2[counter]);
txtEnglish.setText(mBtn3[counter]);
//imgLetter.setBackgroundResource(imgArr[counter]);
Bitmap bm = BitmapFactory.decodeResource(getResources(), imgArr[counter]);
imgLetter.setImageBitmap(bm);
}
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
if(counter>0)
counter--;
changeContent();
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
if(counter<imgArr.length-1)
counter++;
changeContent();
break;
}
}
}
How i can fit to all devices. Can anyone help?? Thanks in advance.
There are couple of possibilities:
use different xml files for different sizes of screen -> check here http://developer.android.com/guide/practices/screens_support.html
you may use scrollview -> http://developer.android.com/reference/android/widget/ScrollView.html
or simply make your layout fit to the smallest screen size you like to support and then just have "a little" unused space on the larger screens.
It really depends on what you need. Probably the most compatible and advanced solution would be 1.
BUT be aware of the fact that EVERY change on the screen layout has to be duplicated for each xml file following this route!
create xml for each device separately. follow this
second way:
create a parent LinearLayout and pass it to the following method
public static boolean isTabletPC(Context context) {
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getWidth() >= 1200) {
isTabletPC = true;
return isTabletPC;
} else {
isTabletPC = false;
return isTabletPC;
}
}
public static void fixUiDeviceDependencies(
Activity act, LinearLayout llParent) {
if (Utilities.isTabletPC(act)) {
Display display = ((WindowManager) act
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
LayoutParams params = (LayoutParams) llParent
.getLayoutParams();
params.width = display.getWidth() / 2;
llParent.setLayoutParams(params);
}
}

Categories

Resources