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.
Related
I'm trying to create a view that allows me to add pictures from the phone photos. In the Layout file I currently have a grid layout with nested LinearLayouts separated into 2 rows x 3 columns. The user will Long Click when they want to delete a photo. The expectation is that after the the image is deleted then the views will reorganize so that there aren't space between the LinearLayout views. Instead I'm getting errors. I think the main issue is that the ImageViews nested withing the LinearLayouts don't have IDs. I've tried using GridViews, swapping ImageView positions, adding copying The ImageView uri to another Imageview. It seems like I'm trying to extend the functionalities to places that they aren't meant to go. Can someone help me ?
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pictureGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="3"
android:orientation="horizontal"
android:rowCount="2"
android:layout_marginTop="330dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:columnOrderPreserved="true">
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_row="0"
android:layout_column="0"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_row="0"
android:layout_column="1"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_row="0"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="0dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_column="0"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="0dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:background="#drawable/custom_border"
android:layout_column="1">
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="0dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:background="#drawable/custom_border"
>
</LinearLayout>
</GridLayout>
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.firebase.storage.FirebaseStorage;
import java.net.URI;
import java.util.ArrayList;
public class RegisterPictures extends android.app.Activity {
FirebaseStorage storage = FirebaseStorage.getInstance("gs://foodz-310506.appspot.com");
private static final int SELECT_IMAGE_GALLERY = 3;
GridLayout table;
View img;
View longClickView;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_pictures);
table = findViewById(R.id.pictureGrid);
for(int i = 0; i < table.getChildCount(); i++) {
img = table.getChildAt(i);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Open Up Gallery
try {
Intent toPhonePhotos = new Intent(Intent.ACTION_GET_CONTENT);
toPhonePhotos.setType("image/*");
toPhonePhotos.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
toPhonePhotos.putExtra(Intent.CATEGORY_OPENABLE, true);
startActivityForResult(Intent.createChooser(toPhonePhotos, "select Picture"), SELECT_IMAGE_GALLERY);
} catch (ActivityNotFoundException e) {
Log.w("TAG", "Unable to start phone gallery");
}
}
});
img.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View view){
try {
Log.wtf("TAG", "long clicking");
LinearLayout v = (LinearLayout) view;
removeSelectedView(v);
sortImages();
} catch (ActivityNotFoundException e) {
Log.wtf("TAG", "wrong");
}
return true;
}
});
j++;
}
}
protected void onStart(){
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Was a photo picked?
if(resultCode != RESULT_CANCELED && data.getData()!=null/*requestCode == SELECT_IMAGE_GALLERY*/) {
ClipData clip = data.getClipData();
//one photo picked
if(clip == null){
Log.e("TAG", "only one image was selected");
Uri uri = data.getData();
photoCounter();
addSinglePhoto(uri);
//Mult photos picked
}else{
photoCounter();
addMultPhoto(clip);
}
}else{
Log.e("TAG", "SHIT IS NOOOT WORKING");
}
}
//Consecutively organizes images without whitespace
private void sortImages(){
for(int i=0; i < table.getChildCount(); i++){
LinearLayout imgHolder = (LinearLayout) table.getChildAt(i);
LinearLayout imgHolder2 = (LinearLayout)table.getChildAt(i+1);
ImageView image = (ImageView)imgHolder.getChildAt(0);
ImageView image2 = (ImageView)imgHolder2.getChildAt(0);
if( image2 != null && image == null){
//Get Drawable from ImageView and set to first ImageView
float x = imgHolder2.getX();
float y = imgHolder2.getY();
Bitmap bitmap = ((BitmapDrawable) image2.getDrawable()).getBitmap();
image.setImageBitmap(bitmap);
imgHolder2.removeAllViews();
/* imgHolder2.setX(imgHolder.getX());
imgHolder2.setY(imgHolder.getY());
imgHolder.setX(x);
imgHolder.setY(y);*/
}
}
}
// Copies ImageView to the previous index
private Drawable CheckView( ImageView iv2) {
Drawable iv2Image = iv2.getDrawable();
return iv2Image;
}
private void removeSelectedView(LinearLayout v){
v.removeAllViews();
}
private void photoCounter(){
}
//Adds one photo
private void addSinglePhoto( Uri uri){
int numOfCells = table.getChildCount();
for(int i=0; i < numOfCells; i++){
Log.e("TAG","Started for statement");
LinearLayout imageHolder = (LinearLayout) table.getChildAt(i);
if(imageHolder.getChildCount() == 0){
imageHolder.addView(imageViewCreater(uri));
i = numOfCells;
}
}
}
//adds multiple photos from Clip
private void addMultPhoto(ClipData clip){
int numOfCells = table.getChildCount();
int j = clip.getItemCount()-1;
for(int i=0; i < numOfCells-1; i++){
LinearLayout cell = (LinearLayout) table.getChildAt(i);
Uri uri = clip.getItemAt(j).getUri();
cell.addView(imageViewCreater(uri));
}
}
private ImageView imageViewCreater(Uri uri){
ImageView grandChildImage = new ImageView(this);
grandChildImage.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
grandChildImage.setImageURI(uri);
return grandChildImage;
}
}
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 !
I have multiple fragments in my Activity. It should initiate only first fragment at start up. It initializes the second one also. More over I move from one fragment to the other though a swipe action. When I swipe from first fragment to the next, third in the row is also initiated.
I have to get data from the server and then populate that fragment. Network request is sent but not for the one for which I am sending but for the fragment next to it.
Please suggest me where I am mistaken...
Thanks in advance.
Following is the code:
Note: Sample code is being used, Please consider the other fragments and their layouts as the same as that for Fragment1.
Main Activity
package com.example.fragments;
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements OnClickListener {
/**
* Constants for tabs
*/
public static final int TAB_SCORES = 0;
public static final int TAB_PAVILION = 1;
public static final int TAB_FRIENDS = 2;
public static final int TAB_OTHER = 3;
public static final int TAB_CROWD = 4;
public static final int TAB_SOCIAL = 5;
private List<Fragment> fragments=null;
private FragmentsAdaptor _adapter;
/** The context object. */
public static Object contextObject = null;
private TableLayout scoresTab, socialTab, pavilionTab, friendsTab, othersTab, crowdTab;
private TextView mScoresTv, mPavilionTv, mFriendsTv, mOtherTv, mCrowdTv, mSocialTv;
private HorizontalScrollView tabsLayout;
private int fragmentPosition;
public ViewPager mViewPager;
private int moveRight = 100;
#Override
protected void onStart() {
super.onStart();
}
/**
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mViewPager = (ViewPager)findViewById(R.id.viewPager);
setViews();
addListeners();
setTab();
addFragments();
}
private void setViews() {
scoresTab = (TableLayout)findViewById(R.id.scores_tab);
pavilionTab = (TableLayout)findViewById(R.id.pavilion_tab);
friendsTab = (TableLayout)findViewById(R.id.friends_tab);
othersTab = (TableLayout)findViewById(R.id.others_tab);
crowdTab = ((TableLayout)findViewById(R.id.crowd_tab));
socialTab = (TableLayout)findViewById(R.id.social_tab);
tabsLayout = (HorizontalScrollView)findViewById(R.id.tabs_layout);
mScoresTv = (TextView)findViewById(R.id.scores);
mPavilionTv = (TextView)findViewById(R.id.pavilion);
mFriendsTv = (TextView)findViewById(R.id.friends);
mOtherTv = (TextView)findViewById(R.id.other);
mCrowdTv = (TextView)findViewById(R.id.crowd);
mSocialTv = (TextView)findViewById(R.id.social);
}
private void addListeners() {
mScoresTv.setOnClickListener(MainActivity.this);
mPavilionTv.setOnClickListener(MainActivity.this);
mFriendsTv.setOnClickListener(MainActivity.this);
mOtherTv.setOnClickListener(MainActivity.this);
mCrowdTv.setOnClickListener(MainActivity.this);
mSocialTv.setOnClickListener(MainActivity.this);
}
private void addFragments(){
fragments = new Vector<Fragment>();
fragments.add(new Fragment1(this));
fragments.add(new Fragment2(this));
fragments.add(new Fragment3(this));
fragments.add(new Fragment4(this));
fragments.add(new Fragment5(this));
fragments.add(new Fragment6(this));
this._adapter = new FragmentsAdaptor(super.getSupportFragmentManager(), fragments);
mViewPager.setAdapter(this._adapter);
}
#Override
public void onClick(View v){
onTabsClick(v);
}
public void onTabsClick(View v) {
//reset layout of all the text views
resetlayouts();
if(v == mScoresTv) {
if(mViewPager.getCurrentItem() != TAB_SCORES) {
changeTab(TAB_SCORES);
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mCrowdTv) {
if(mViewPager.getCurrentItem() != TAB_CROWD) {
changeTab(TAB_CROWD);
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mFriendsTv) {
if(mViewPager.getCurrentItem() != TAB_FRIENDS) {
changeTab(TAB_FRIENDS);
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mOtherTv) {
if(mViewPager.getCurrentItem() != TAB_OTHER) {
changeTab(TAB_OTHER);
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mPavilionTv) {
if(mViewPager.getCurrentItem() != TAB_PAVILION) {
changeTab(TAB_PAVILION);
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mSocialTv) {
if(mViewPager.getCurrentItem() != TAB_SOCIAL) {
changeTab(TAB_SOCIAL);
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
}
}
}
private void changeTab(int tabType) {
mViewPager.setCurrentItem(tabType);
System.out.println("tab to change to: " + tabType);
}
private void resetlayouts(){
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
othersTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
socialTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
mScoresTv.setTextColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.black));
}
private void setTab() {
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
System.out.println("setTab:::::::::::::::::::::::::::::::::::" + position);
int previousFragment = fragmentPosition;
if(previousFragment < position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() + moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
if(previousFragment > position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() - moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
fragmentPosition = position;
resetlayouts();
System.out.println("In on tab change listener!");
switch(position) {
case TAB_SCORES:
System.out.println("scores");
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
case TAB_PAVILION:{
System.out.println("pavilion");
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_FRIENDS:{
System.out.println("friends");
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_OTHER:{
System.out.println("others");
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_CROWD:{
System.out.println("crowd");
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_SOCIAL:{
System.out.println("social");
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
}
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null)
fragment.onPause();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
FragmentsAdapter
package com.example.fragments;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentsAdaptor extends FragmentPagerAdapter {
private List<Fragment> fragments;
/**
* #param fm
* #param fragments
*/
public FragmentsAdaptor(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.fragments.size();
}
public Fragment getFragment(int position) {
return this.fragments.get(position);
}
}
Fragment1
package com.example.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
public class Fragment1 extends Fragment implements OnClickListener {
private Context context;
public Fragment1() {}
public Fragment1(Context contex) {
this.context=contex;
}
#Override
public void onClick(View arg0) {
}
#Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
System.out.println("Fragment1.onInflate() called................");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
System.out.println("Fragment1.onAttach() called................");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Fragment1.onCreate() called................");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
System.out.println("Fragment1.onCreateView() called................");
View root = (View) inflater.inflate(R.layout.fragment1_screen, null);
updateArticleView(root);
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("Fragment1.onActivityCreated() called................");
}
#Override
public void onStart() {
super.onStart();
System.out.println("Fragment1.onStart() called................");
}
#Override
public void onResume() {
super.onResume();
System.out.println("Fragment1.onResume() called................");
}
#Override
public void onPause() {
super.onPause();
System.out.println("Fragment1.onPause() called................");
onDestroyView();
}
#Override
public void onDestroyView() {
super.onDestroyView();
System.out.println("Fragment1.onDestroyView() called................");
onDestroy();
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Fragment1.onDestroy() called................");
onDetach();
}
#Override
public void onDetach() {
super.onDetach();
System.out.println("Fragment1.onDetach() called................");
}
public void updateArticleView(View view) {
}
}
Main Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<HorizontalScrollView
android:id="#+id/tabs_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="2dp"
android:paddingRight="2dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<!-- First Tab -->
<TableLayout
android:id="#+id/scores_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/scores"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Scores"
android:textColor="#android:color/white"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Second Tab -->
<TableLayout
android:id="#+id/pavilion_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/pavilion"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="25dp"
android:text="Pavilion"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Third Tab -->
<TableLayout
android:id="#+id/friends_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/friends"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Friends"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fourth Tab -->
<TableLayout
android:id="#+id/others_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/other"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Other"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fifth Tab -->
<TableLayout
android:id="#+id/crowd_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/crowd"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Crowd"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="0px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Sixth Tab -->
<TableLayout
android:id="#+id/social_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/social"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Social"
android:textColor="#android:color/black"
android:textSize="12sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</HorizontalScrollView>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#id/tabs_layout"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" >
</android.support.v4.view.ViewPager>
Fragment layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relLay"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/text1"
android:text="Fragment1 Text"
android:textColor="#android:color/black"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I achieved it by placing the following code at the end of OnPageChangeListener.onPageSelected()
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null) {
fragment.onPause();
}
I am using onPause() in the following way
public void onPause(){
super.onPause();
onDestroyView();
}
public void onDestroyView() {
super.onDestroyView();
onDestroy();
}
public void onDestroy() {
super.onDestroy();
onDetach();
}
public void onDetach() {
super.onDetach();
}
this is a known issue, that ViewPager(FragmentAdapter(Fragements)) created and destroyed according to the actual page.
I also came across with this situation, furthermore the data (Object) not referenced, because of a destroy will be collected by the GC so this is difficult.
I would use a static object at the main Activity and with the onRetainNonConfigurationInstance method I would save and load Fragment state.
Also found another solution which concentrated on the passed data between the Fragments (A,B and passed String data) here.
I hope one of these solutions are suitable for you!
Just call setOffscreenPageLimit() in onCreate() (after initializing ViewPager). The OffscreenPageLimit sets the number of pages that should be retained to either side of the current page. Set the minimum number of fragments you want to initiate either side.
I'm developing an android application. It is an exam app. When a user clicks an answer, the application changes the layout with $setContentView(); in same activity.
But it gives an error for layout Caused by: java.lang.NumberFormatException: unable to parse '#2131230721' as integer
My layout file is below, if you need I can put my project myserver. And I can paste my activity code, but it's a basic setContentView() only. I guess one of my id's is causing the error but i couldn't find it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/soruNoIleriVeGeri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:id="#+id/SoruLayout"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/OncekiSoru"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/qIPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/back_button"
android:onClick="qIPrevious"
android:paddingLeft="5dp" />
</LinearLayout>
<LinearLayout
android:layout_width="57dp"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/about_question" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_favourite" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/goToQuestion"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:onClick="onshowQuestion"
android:src="#drawable/show_question" />
</LinearLayout>
<LinearLayout
android:layout_width="50dp"
android:layout_height="45dp"
android:layout_weight="0.57" >
<ImageButton
android:id="#+id/homeButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/tab_home"
android:onClick="goHome" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/next_button"
android:onClick="qINextQuestion" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/resultIconPlain"
android:layout_width="84dp"
android:layout_height="fill_parent"
android:paddingLeft="20dp" >
</LinearLayout>
<LinearLayout
android:layout_width="234dp"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/resultView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.13"
android:gravity="center_horizontal"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="59dp"
android:background="#drawable/question_top_plain" >
<LinearLayout
android:id="#+id/dogruCevap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikDogruCevap"
android:layout_width="126dp"
android:layout_height="wrap_content"
android:text="#string/StatikDogruCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.01" >
<TextView
android:id="#+id/dogruCevapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingRight="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/cevabiniz"
android:layout_width="fill_parent"
android:layout_height="54dp"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/cevabinizView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikCevap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/StatikCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="350px"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/dogruCevapAyrinti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.60"
android:isScrollContainer="true"
android:minHeight="400px"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/dogruCevapAyrintiView"
android:layout_width="fill_parent"
android:layout_height="324dp"
android:scrollHorizontally="false"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" >
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
Here is error codes and myActivity sorry for Turkish variable names
at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
java.lang.reflect.InvocationTargetException
at android.widget.TextView.<init>(TextView.java:320)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
at android.view.LayoutInflater.createView(LayoutInflater.java:500)
... 41 more
java.lang.NumberFormatException: unable to parse '#2131230721' as integer
at java.lang.Integer.parse(Integer.java:374)
at java.lang.Integer.parseInt(Integer.java:363)
at com.android.internal.util.XmlUtils.convertValueToInt(XmlUtils.java:121)
at android.content.res.TypedArray.getInt(TypedArray.java:201)
at android.widget.TextView.<init>(TextView.java:647)
package com.eandroid.workingSet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.eandroid.entity.Question;
public class QuestionInterfaceActivity extends Activity {
LinearLayout layoutForA;
LinearLayout layoutForB;
LinearLayout layoutForC;
LinearLayout layoutForD;
LinearLayout layoutForE;
LinearLayout choiceATotalPlain;
LinearLayout choiceBTotalPlain;
LinearLayout choiceCTotalPlain;
LinearLayout choiceDTotalPlain;
LinearLayout choiceETotalPlain;
LinearLayout allTotalPlain;
List<Question> questionList = new ArrayList<Question>();
Node node = null;
NodeList nodeList = null;
NodeList nodeListForTestInfo = null;
InputStream is = null;
private TextView choiceA;
private TextView choiceB;
private TextView choiceC;
private TextView choiceD;
private TextView choiceE;
private TextView questionText;
private TextView soruIdText;
private TextView soruIdEv;
private TextView soruBilgileriView;
private TextView cevabinizView;
private TextView dogruCevapView;
private TextView dogruCevapAyrintiView;
private TextView resultView;
private int currentQuestionIndex;
Question currentQuestion = null;
private String testName = null;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
HttpResponse response;
InputStream contentStream;
private String rightAnswers = "";
private String userAnswers = "";
private String resultOfAnswers = "";
private String userId = "1";
private static String testRelationId;
private LinearLayout resultIconPlain;
private static String willPostUrl =
"http://balabanhafriyat.com/SchoolProjectWebSide/postFromPhone/SendDataFromPhone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
}
settleOrientation();
Bundle extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("testName");
}
try {
is = getAssets().open(testName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("question");
nodeListForTestInfo = doc.getElementsByTagName("testInfo");
Node testNode = nodeListForTestInfo.item(0);
testRelationId = parseItToStringByName(testNode, "testRelationId");
} catch (Exception e) {
e.printStackTrace();
}
currentQuestionIndex = 1;
showQuestion();
}
public void settleOrientation() {
int setLayout = getResources().getConfiguration().orientation;
switch (setLayout) {
case 1:
setContentView(R.layout.buttontry);
loadDesign();
break;
case 2:
setContentView(R.layout.buttontry);
break;
default:
break;
}
}
public void callEvaluationActivity(int optionToSeeQuestion,
String userAnswer) {
setContentView(R.layout.evaluation_screen);
// resultView = (TextView) findViewById(R.id.resultView);
cevabinizView = (TextView) findViewById(R.id.cevabiniz);
dogruCevapView = (TextView) findViewById(R.id.rightAnswer);
dogruCevapAyrintiView = (TextView)
findViewById(R.id.dogruCevapAyrintiView);
// soruBilgileriView.setText(currentQuestion.getShortInfo());
dogruCevapAyrintiView.setText(currentQuestion.getRightAnswerDetail());
dogruCevapView.setText(currentQuestion.getRightAnswer());
if (optionToSeeQuestion == 2) {
cevabinizView.setText(userAnswer);
if (currentQuestion.getRightAnswer().equals(userAnswer)) {
resultView.setTextColor(Color.GREEN);
resultView.setText("Doğru Cevap");
resultOfAnswers = resultOfAnswers + "1$";
} else {
resultView.setTextColor(Color.RED);
resultView.setText("Cevap Yanlış !!! ");
resultOfAnswers = resultOfAnswers + "0$";
}
userAnswers = userAnswers + userAnswer + "$";
rightAnswers = rightAnswers + currentQuestion.getRightAnswer()
+ "$";
}
}
public void loadDesign() {
allTotalPlain = (LinearLayout) findViewById(R.id.allTotalPlain);
allTotalPlain.setBackgroundResource(R.drawable.yellow_button);
choiceATotalPlain = (LinearLayout) findViewById(R.id.choiceTotalPlain);
choiceBTotalPlain = (LinearLayout) findViewById(R.id.choiceBTotalPlain);
choiceCTotalPlain = (LinearLayout) findViewById(R.id.choiceCTotalPlain);
choiceDTotalPlain = (LinearLayout) findViewById(R.id.choiceDTotalPlain);
choiceETotalPlain = (LinearLayout) findViewById(R.id.choiceETotalPlain);
layoutForA = (LinearLayout) findViewById(R.id.abuttonLayout);
layoutForB = (LinearLayout) findViewById(R.id.bButtonLayout);
layoutForC = (LinearLayout) findViewById(R.id.cButtonLayout);
layoutForD = (LinearLayout) findViewById(R.id.dButtonLayout);
layoutForE = (LinearLayout) findViewById(R.id.ebuttonLayout);
createButton("A");
createButton("B");
createButton("C");
createButton("D");
createButton("E");
}
private void showQuestion() {
questionText = (TextView) findViewById(R.id.soruTextView);
choiceA = (TextView) findViewById(R.id.choiceA);
choiceB = (TextView) findViewById(R.id.choiceB);
choiceC = (TextView) findViewById(R.id.choiceC);
choiceD = (TextView) findViewById(R.id.choiceD);
choiceE = (TextView) findViewById(R.id.choiceE);
currentQuestion = setQuestionFieldById(currentQuestionIndex);
questionText.setText(currentQuestion.getQuestionText());
choiceA.setText(currentQuestion.getChoiceA());
choiceB.setText(currentQuestion.getChoiceB());
choiceC.setText(currentQuestion.getChoiceC());
choiceD.setText(currentQuestion.getChoiceD());
choiceE.setText(currentQuestion.getChoiceE());
/*
* consumerAnswer .setOnCheckedChangeListener(new
* OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup
* group, int checkedId) { if (choiceA.getId() == checkedId) {
* approveAnswer(2, "A"); } if (choiceB.getId() == checkedId) {
*
* approveAnswer(2, "B"); } if (choiceC.getId() == checkedId) {
*
* approveAnswer(2, "C"); } if (choiceD.getId() == checkedId) {
*
* approveAnswer(2, "D"); } if (choiceE.getId() == checkedId) {
*
* approveAnswer(2, "E"); } } });
*/
}
private void approveAnswer(int optionToSeeQuestion, final String userChoice) {
callEvaluationActivity(optionToSeeQuestion, userChoice);
}
// Eger optionToSeeQuestion 1 ise kullanıcının cevap karsılastırılması
// yapılmamalı 2 ise yapılmalı
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 999) {
if (data.hasExtra("action")) {
String aim = data.getExtras().getString("aim");
Toast.makeText(this, "Ne yapmak istiyorsunuz" + aim,
Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void qINextQuestion(View view) {
if (currentQuestionIndex == nodeList.getLength() - 1) {
Toast.makeText(QuestionInterfaceActivity.this, "Son Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex++;
settleOrientation();
showQuestion();
}
}
public void qIPrevious(View view) {
if (currentQuestionIndex == 1) {
Toast.makeText(QuestionInterfaceActivity.this, "İlk Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex--;
settleOrientation();
showQuestion();
}
}
public Question setQuestionFieldById(int questionId) {
Question q = new Question();
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
int idFromXml = Integer.parseInt(parseItToStringByName(node,
"questionNumber"));
if (questionId == idFromXml) {
q.setQuestionId(questionId);
q.setChoiceA(parseItToStringByName(node, "choiceA"));
q.setChoiceB(parseItToStringByName(node, "choiceB"));
q.setChoiceC(parseItToStringByName(node, "choiceC"));
q.setChoiceD(parseItToStringByName(node, "choiceD"));
q.setChoiceE(parseItToStringByName(node, "choiceE"));
q.setQuestionText(parseItToStringByName(node,
"questionText"));
q.setRightAnswer(parseItToStringByName(node,
"rightAnswer"));
q.setRightAnswerDetail(parseItToStringByName(node,
"answerDetail"));
}
}
return q;
}
public String parseItToStringByName(Node node, String nodeName) {
Element mainELement = (Element) node;
NodeList questionList = mainELement.getElementsByTagName(nodeName);
Element questionElement = (Element) questionList.item(0);
NodeList question = questionElement.getChildNodes();
String result = question.item(0).getNodeValue().replaceAll("\n", "")
.replaceAll("\t", "");
result.trim();
return result;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.landscapequestion);
showQuestion();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.buttontry);
showQuestion();
}
}
#Override
public void onBackPressed() {
beforeQuitProcess();
super.onBackPressed();
}
public void beforeQuitProcess() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("testId", testRelationId));
postParameters
.add(new BasicNameValuePair("rightAnswers", rightAnswers));
postParameters.add(new BasicNameValuePair("userAnswers", userAnswers));
postParameters.add(new BasicNameValuePair("userAnswerAndResult",
resultOfAnswers));
postParameters.add(new BasicNameValuePair("userId", userId));
PostDataToServer postDataToServer = new PostDataToServer();
HttpResponse response = postDataToServer.postData(willPostUrl,
postParameters);
contentStream = postDataToServer.parseHttpResponseToStream(response);
String responseFromServer = postDataToServer
.convertStreamToString(contentStream);
if (responseFromServer != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Kayıt Edildi",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Çıktı Hacı",
Toast.LENGTH_SHORT).show();
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
finish();
}
public void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
#Override
protected void onResume() {
super.onResume();
}
public void onshowAnswer(View v) {
callEvaluationActivity(1, "A");
}
public void onshowQuestion(View view) {
setContentView(R.layout.buttontry);
loadDesign();
showQuestion();
}
public void goHome(View view) {
beforeQuitProcess();
Intent intent = new Intent(QuestionInterfaceActivity.this,
LoginEvaluation.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
public void createButton(final String text) {
Button button = new Button(this);
button.setTextColor(Color.parseColor("#000000"));
button.setBackgroundResource(R.drawable.button_selector);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
clickMeMyFriend(view, text);
}
});
button.setText(text);
if (text.equals("A")) {
layoutForA.addView(button);
}
if (text.equals("B")) {
layoutForB.addView(button);
}
if (text.equals("C")) {
layoutForC.addView(button);
}
if (text.equals("D")) {
layoutForD.addView(button);
}
if (text.equals("E")) {
layoutForE.addView(button);
}
}
private void clickMeMyFriend(View view, String chooice) {
if (chooice.equals("A")) {
approveAnswer(2, "A");
}
if (chooice.equals("B")) {
approveAnswer(2, "B");
}
if (chooice.equals("C")) {
approveAnswer(2, "C");
}
if (chooice.equals("D")) {
approveAnswer(2, "D");
}
if (chooice.equals("E")) {
approveAnswer(2, "E");
}
}
public void onTotalAClick(View view) {
switch (view.getId()) {
case R.id.choiceTotalPlain:
choiceATotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "A");
break;
case R.id.choiceBTotalPlain:
choiceBTotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "B");
break;
case R.id.choiceCTotalPlain:
approveAnswer(2, "C");
choiceCTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceDTotalPlain:
approveAnswer(2, "D");
choiceDTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceETotalPlain:
approveAnswer(2, "E");
choiceETotalPlain.setBackgroundResource(R.drawable.black_button);
break;
default:
break;
}
}
}
Thanks for all help
Thanks too much for your effort Barak , Alex Lockwood and the others too i recode my xml layout upon your advices nothing changed but i could seen an error cant be realize before due to my unnecassary LinearLayout block .Whatever the error is :there is a statement in my layout
android:textStyle="#style/boldText"
in this statement the value can be only bold or normal etc .this statement should be like
style="#style/choiceStyle"
thanks for your help .I decided not to work after 00:00
Are you saying you are trying to use setContentView more than once in an activity?
From everything I have read, that won't work.
If you want to change your UI without switching activities you need to use fragments, or put all of the Views you want into your one layout and hide/show only the relevant ones for each portion of your activity with setVisibility().
The reason why you are getting a NumberFormatException is because #2131230721 is not an integer. Here's what you should do:
Re-do your entire XML layout. I am not kidding... the layout you have posted is an absolute disaster. Sorry if that's mean, but I can't let you go on thinking this is the correct way to make your layouts :).
From what I can tell, you are wrapping every single view in a LinearLayout to achieve some sort of margin/padding effect. This is what the android:margin and android:padding attributes are for. Don't over-complicate things with weird android:layout_weight values, as this will make your app run slower when your layout gets inflated. If you ever find that your XML has more than 3 or 4 LinearLayouts you should take a step back and see if you are missing an easier, more efficient solution. It is frowned upon to have nested LinearLayouts too, as it is expensive to inflate these at runtime and will drain your battery as a result.
Do a Project --> Clean and restart eclipse.
Post more information. For example, your entire logcat output would be nice (not just one line). Posting your code is almost always a good idea too. It is very difficult to understand the problem from the tiny amount of information you have provided. Remember that it is beneficial to you to provide as much information as you can because the more information we have, the more likely it is that we can help answer your question. You should also provide us with line numbers and/or indicate on which lines the errors occur.
Oh yeah, and welcome to StackOverflow... :P
Is it possible that the weights are causing the problems? I've never used weights as decimals before, I thought they had to be real numbers, I mean like 1 or 2 etc. Floor numbers. Just a thought
From what I can see its something to do with a number and a text view, this could either be the text views color, weight, ID or style.
What's in style/boldText and style/rightAnswer?
You layout file does Start with a LinearLayout and defines a xmlns:android="http://schemas.android.com/apk/res/android", but you end up with a closing <ScrollView> Tag? Is there anything missing? Plus, javaCode would be great!
By the way: did u try to "clean" you project in eclipse, using Project->Clean?
This resets the R file and often helps!
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);
}
}