Search in sources :

Example 36 with TabLayout

use of android.support.design.widget.TabLayout in project ChatExchange by HueToYou.

the class MainActivity method setup.

private void setup() {
    mTabLayout = (TabLayout) findViewById(R.id.main_tabs);
    try {
        TabLayout.Tab home = mTabLayout.newTab().setText(getResources().getText(R.string.generic_accounts)).setIcon(new BitmapDrawable(Resources.getSystem(), Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), 144, 144, true))).setTag("home");
        //            TabLayout.Tab add = mTabLayout.newTab()
        //                    .setText(getResources()
        //                            .getText(R.string.activity_main_add_chat))
        //                    .setIcon(new BitmapDrawable(Resources.getSystem(), Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), 144, 144, true)))
        //                    .setTag("add");
        //            mTabLayout.addTab(add);
        mTabLayout.addTab(home);
    //            home.select();
    } catch (Exception e) {
        e.printStackTrace();
    }
    mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.add_chat_fab);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showAddTabDialog();
        }
    });
    HandleAdds handleAdds = new HandleAdds();
    CancelTask cancel = new CancelTask(handleAdds);
    mHandler.postDelayed(cancel, 10000);
    handleAdds.execute();
    mAccountManager = AccountManager.get(this);
    if (mAccountManager.getAccounts().length > 0) {
        //            int tabIndex = mSharedPrefs.getInt("tabIndex", 0);
        addFragmentByTab(mTabLayout.getTabAt(HOME_INDEX));
    } else {
        startActivity(new Intent(this, AuthenticatorActivity.class));
        finish();
    }
    tabListener();
    if (mAddTab != null && mIntent != null && mIntent.getAction() != null) {
        final String action = mIntent.getAction();
        if (action.equals(Intent.ACTION_MAIN)) {
            ReAddTabs reAddTabs = new ReAddTabs();
            CancelTask cancelTask = new CancelTask(reAddTabs);
            mHandler.postDelayed(cancelTask, 10000);
            reAddTabs.execute();
        }
    }
}
Also used : Intent(android.content.Intent) BitmapDrawable(android.graphics.drawable.BitmapDrawable) View(android.view.View) AuthenticatorActivity(com.huetoyou.chatexchange.auth.AuthenticatorActivity) TabLayout(android.support.design.widget.TabLayout) FloatingActionButton(android.support.design.widget.FloatingActionButton)

Example 37 with TabLayout

use of android.support.design.widget.TabLayout in project TaEmCasa by Dionen.

the class MenuActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu_main);
    /* ORGANIZA AS ABAS */
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    // clear all scroll flags
    params.setScrollFlags(0);
    /* BOTAO DE NOTIFICAÇÃO */
    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View view) {
            Snackbar.make(view, "Tem pessoas interessadas em algumas de suas vagas!", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            animator.setRepeatCount(1);
            Animation fadeout = new AlphaAnimation(1.f, 0.f);
            fadeout.setDuration(500);
            view.startAnimation(fadeout);
            view.postDelayed(new Runnable() {

                @Override
                public void run() {
                    view.setVisibility(View.GONE);
                }
            }, 500);
        }
    });
    /* ANIMAÇÃO DO BOTÃO */
    animator = ObjectAnimator.ofInt(fab, "backgroundTint", Color.rgb(255, 0, 0), Color.rgb(255, 255, 255), Color.rgb(255, 0, 0));
    animator.setDuration(1000);
    animator.setEvaluator(new ArgbEvaluator());
    animator.setInterpolator(new DecelerateInterpolator(2));
    animator.setRepeatCount(Animation.INFINITE);
    animator.addUpdateListener(new ObjectAnimator.AnimatorUpdateListener() {

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            int animatedValue = (int) animation.getAnimatedValue();
            fab.setBackgroundTintList(ColorStateList.valueOf(animatedValue));
        }
    });
    animator.start();
    /* RECEBE OS DADOS DO USUÁRIO */
    Intent intent = getIntent();
    user_id = intent.getStringExtra("user_id");
    user_nome = intent.getStringExtra("nome");
    user_sobrenome = intent.getStringExtra("sobrenome");
    user_email = intent.getStringExtra("email");
    Toast toast = Toast.makeText(MenuActivity.this, "Olá, " + user_nome + " " + user_sobrenome + "!\nSeu ID: " + user_id + "\nSeu email: " + user_email, Toast.LENGTH_LONG);
    toast.show();
}
Also used : DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ObjectAnimator(android.animation.ObjectAnimator) ArgbEvaluator(android.animation.ArgbEvaluator) Intent(android.content.Intent) ValueAnimator(android.animation.ValueAnimator) View(android.view.View) AlphaAnimation(android.view.animation.AlphaAnimation) Toast(android.widget.Toast) TabLayout(android.support.design.widget.TabLayout) Animation(android.view.animation.Animation) AlphaAnimation(android.view.animation.AlphaAnimation) AppBarLayout(android.support.design.widget.AppBarLayout) Toolbar(android.support.v7.widget.Toolbar)

Example 38 with TabLayout

use of android.support.design.widget.TabLayout in project twicalico by moko256.

the class MainActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    subscription = new CompositeSubscription();
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.getChildAt(0).setOnClickListener(v -> {
        Fragment fragment = getMainFragment();
        if (fragment instanceof MovableTopInterface) {
            ((MovableTopInterface) fragment).moveToTop();
        }
    });
    drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    drawer.addDrawerListener(new DrawerLayout.DrawerListener() {

        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            if (isDrawerAccountsSelection) {
                changeIsDrawerAccountsSelection();
            }
        }

        @Override
        public void onDrawerStateChanged(int newState) {
        }
    });
    navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(item -> {
        int id = item.getItemId();
        if (!item.isChecked()) {
            switch(id) {
                case R.id.nav_timeline:
                    replaceFragment(new HomeTimeLineFragment());
                    break;
                case R.id.nav_mentions:
                    replaceFragment(new MentionsFragment());
                    break;
                case R.id.nav_account:
                    startMyUserActivity();
                    break;
                case R.id.nav_follow_and_follower:
                    replaceFragment(new MyFollowFollowerFragment());
                    break;
                case R.id.nav_like:
                    replaceFragment(UserLikeFragment.newInstance(GlobalApplication.userId));
                    break;
                case R.id.nav_settings:
                    startActivity(new Intent(this, SettingsActivity.class));
                    break;
            }
        }
        drawer.closeDrawer(GravityCompat.START);
        return (id != R.id.nav_settings) && (id != R.id.nav_account);
    });
    headerView = navigationView.inflateHeaderView(R.layout.nav_header_main);
    userNameText = headerView.findViewById(R.id.user_name);
    userIdText = headerView.findViewById(R.id.user_id);
    userImage = headerView.findViewById(R.id.user_image);
    userBackgroundImage = headerView.findViewById(R.id.user_bg_image);
    userBackgroundImage.setOnClickListener(v -> changeIsDrawerAccountsSelection());
    updateDrawerImage();
    accountListView = new RecyclerView(this);
    accountListView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    accountListView.setLayoutManager(new LinearLayoutManager(this));
    accountListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    accountListView.setVisibility(View.GONE);
    navigationView.addHeaderView(accountListView);
    SelectAccountsAdapter adapter = new SelectAccountsAdapter(this);
    adapter.setOnImageButtonClickListener(accessToken -> {
        drawer.closeDrawer(GravityCompat.START);
        if (accessToken.getUserId() != GlobalApplication.userId) {
            PreferenceManager.getDefaultSharedPreferences(this).edit().putString("AccountKey", accessToken.getKeyString()).apply();
            ((GlobalApplication) getApplication()).initTwitter(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        }
    });
    adapter.setOnAddButtonClickListener(v -> {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("AccountKey", "-1").apply();
        GlobalApplication.twitter = null;
        startActivity(new Intent(this, OAuthActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
    });
    adapter.setOnRemoveButtonClickListener(v -> new AlertDialog.Builder(this).setMessage(R.string.confirm_logout).setCancelable(true).setPositiveButton(R.string.do_logout, (dialog, i) -> {
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        TokenSQLiteOpenHelper helper = new TokenSQLiteOpenHelper(this);
        helper.deleteAccessToken(helper.getAccessToken(defaultSharedPreferences.getString("AccountKey", "-1")));
        int point = helper.getSize() - 1;
        if (point != -1) {
            AccessToken accessToken = helper.getAccessTokens()[point];
            defaultSharedPreferences.edit().putString("AccountKey", accessToken.getKeyString()).apply();
            ((GlobalApplication) getApplication()).initTwitter(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        } else {
            adapter.getOnAddButtonClickListener().onClick(v);
        }
        helper.close();
    }).setNeutralButton(R.string.back, (dialog, i) -> dialog.cancel()).show());
    accountListView.setAdapter(adapter);
    subscription.add(Single.create(singleSubscriber -> {
        TokenSQLiteOpenHelper helper = new TokenSQLiteOpenHelper(this);
        AccessToken[] accessTokens = helper.getAccessTokens();
        helper.close();
        ArrayList<Pair<User, AccessToken>> r = new ArrayList<>(accessTokens.length);
        for (AccessToken accessToken : accessTokens) {
            long id = accessToken.getUserId();
            CachedUsersSQLiteOpenHelper userHelper = new CachedUsersSQLiteOpenHelper(this, id, accessToken.getType() == Type.TWITTER);
            User user = userHelper.getCachedUser(id);
            if (user == null) {
                try {
                    user = ((GlobalApplication) getApplication()).getTwitterInstance(accessToken).verifyCredentials();
                    userHelper.addCachedUser(user);
                } catch (TwitterException e) {
                    singleSubscriber.onError(e);
                    return;
                } finally {
                    userHelper.close();
                }
            }
            r.add(new Pair<>(user, accessToken));
        }
        singleSubscriber.onSuccess(r);
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
        ArrayList<Pair<User, AccessToken>> pairs = (ArrayList<Pair<User, AccessToken>>) o;
        adapter.getImagesList().addAll(pairs);
        adapter.notifyDataSetChanged();
    }, Throwable::printStackTrace));
    findViewById(R.id.fab).setOnClickListener(v -> startActivity(new Intent(this, PostActivity.class)));
    tabLayout = findViewById(R.id.toolbar_tab);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            Fragment fragment = ((FragmentPagerAdapter) ((UseTabsInterface) getMainFragment()).getTabsViewPager().getAdapter()).getFragment(tab.getPosition());
            if (fragment instanceof MovableTopInterface) {
                ((MovableTopInterface) fragment).moveToTop();
            }
        }
    });
    tweetListViewPool = new RecyclerView.RecycledViewPool();
    userListViewPool = new RecyclerView.RecycledViewPool();
    getSupportFragmentManager().addOnBackStackChangedListener(() -> attachFragment(getMainFragment()));
    if (savedInstanceState == null) {
        prepareFragment();
    }
}
Also used : NavigationView(android.support.design.widget.NavigationView) LinearLayout(android.widget.LinearLayout) Type(com.github.moko256.twicalico.entity.Type) Bundle(android.os.Bundle) ImageView(android.widget.ImageView) CachedUsersSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedUsersSQLiteOpenHelper) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) NonNull(android.support.annotation.NonNull) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) TabLayout(android.support.design.widget.TabLayout) GravityCompat(android.support.v4.view.GravityCompat) Single(rx.Single) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) User(twitter4j.User) View(android.view.View) TwitterException(twitter4j.TwitterException) PreferenceManager(android.preference.PreferenceManager) DrawerLayout(android.support.v4.widget.DrawerLayout) AccessToken(com.github.moko256.twicalico.entity.AccessToken) Fragment(android.support.v4.app.Fragment) ActivityOptionsCompat(android.support.v4.app.ActivityOptionsCompat) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) FragmentManager(android.support.v4.app.FragmentManager) AlertDialog(android.support.v7.app.AlertDialog) TextView(android.widget.TextView) SharedPreferences(android.content.SharedPreferences) Toolbar(android.support.v7.widget.Toolbar) Pair(android.support.v4.util.Pair) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) FragmentPagerAdapter(com.github.moko256.twicalico.widget.FragmentPagerAdapter) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) User(twitter4j.User) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) ArrayList(java.util.ArrayList) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) Fragment(android.support.v4.app.Fragment) AccessToken(com.github.moko256.twicalico.entity.AccessToken) TabLayout(android.support.design.widget.TabLayout) DrawerLayout(android.support.v4.widget.DrawerLayout) TwitterException(twitter4j.TwitterException) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) Pair(android.support.v4.util.Pair) SharedPreferences(android.content.SharedPreferences) CachedUsersSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedUsersSQLiteOpenHelper) Intent(android.content.Intent) NavigationView(android.support.design.widget.NavigationView) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) LinearLayout(android.widget.LinearLayout)

Example 39 with TabLayout

use of android.support.design.widget.TabLayout in project Shuttle by timusus.

the class BaseWidgetConfigure method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Aesthetic.isFirstTime(this)) {
        Aesthetic.get(this).activityTheme(R.style.WallpaperTheme).isDark(false).colorPrimaryRes(R.color.md_blue_500).colorAccentRes(R.color.md_amber_300).colorStatusBarAuto().apply();
    }
    setContentView(R.layout.activity_widget_config);
    Bundle extras = this.getIntent().getExtras();
    if (extras != null) {
        appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
        finish();
    }
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    layoutId = prefs.getInt(getLayoutIdString() + appWidgetId, getWidgetLayouts()[0]);
    backgroundColor = prefs.getInt(BaseWidgetProvider.ARG_WIDGET_BACKGROUND_COLOR + appWidgetId, ContextCompat.getColor(this, R.color.white));
    textColor = prefs.getInt(BaseWidgetProvider.ARG_WIDGET_TEXT_COLOR + appWidgetId, Color.WHITE);
    showAlbumArt = prefs.getBoolean(BaseWidgetProvider.ARG_WIDGET_SHOW_ARTWORK + appWidgetId, true);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    layouts = getWidgetLayouts();
    // Instantiate a ViewPager and a PagerAdapter.
    pager = findViewById(R.id.pager);
    adapter = new WidgetPagerAdapter(getSupportFragmentManager());
    pager.setAdapter(adapter);
    TabLayout tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(pager);
    pager.addOnPageChangeListener(this);
    Button doneButton = findViewById(R.id.btn_done);
    doneButton.setOnClickListener(this);
    backgroundColorButton = findViewById(R.id.btn_background_color);
    backgroundColorButton.setOnClickListener(this);
    textColorButton = findViewById(R.id.btn_text_color);
    textColorButton.setOnClickListener(this);
    CheckBox showAlbumArtCheckbox = findViewById(R.id.checkBox1);
    showAlbumArtCheckbox.setOnCheckedChangeListener(this);
    CheckBox invertedIconsCheckbox = findViewById(R.id.checkBox2);
    invertedIconsCheckbox.setOnCheckedChangeListener(this);
    seekBar = findViewById(R.id.seekBar1);
    seekBar.setOnSeekBarChangeListener(this);
    updateWidgetUI();
}
Also used : ImageButton(android.widget.ImageButton) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton) Bundle(android.os.Bundle) TabLayout(android.support.design.widget.TabLayout) CheckBox(android.widget.CheckBox) Toolbar(android.support.v7.widget.Toolbar)

Example 40 with TabLayout

use of android.support.design.widget.TabLayout in project MadMax by deviz92.

the class PendingExpenseDetailActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "OnCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pending_expense_detail);
    Intent intent = getIntent();
    expenseID = intent.getStringExtra("expenseID");
    // intent.getStringExtra("userID");
    userID = MainActivity.getCurrentUID();
    fab = (FloatingActionButton) findViewById(R.id.fab);
    updateFab(0);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setBackgroundColor(0x0000FF00);
    // Get a support ActionBar corresponding to this toolbar
    ActionBar ab = getSupportActionBar();
    // Enable the Up button
    ab.setDisplayHomeAsUpEnabled(true);
    // insert tabs and current fragment in the main layout
    // mainView.addView(getLayoutInflater().inflate(R.layout.activity_expense_detail, null));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText(R.string.expense_detail));
    tabLayout.addTab(tabLayout.newTab().setText(R.string.comments));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager = (ViewPager) findViewById(R.id.expense_detail_view_pager);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Log.d(TAG, String.valueOf(tab.getPosition()));
            updateFab(tab.getPosition());
            Log.d(TAG, "tab.getPosition() " + tab.getPosition());
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
    ExpenseDetailPagerAdapter adapter = new ExpenseDetailPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), expenseID, TAG);
    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(0);
    imageView = (ImageView) findViewById(R.id.img_photo);
    amountTextView = (TextView) findViewById(R.id.tv_amount);
    creatorNameTextView = (TextView) findViewById(R.id.tv_creator_name);
    groupTextView = (TextView) findViewById(R.id.tv_group_name);
    expenseNameTextView = (TextView) findViewById(R.id.tv_pending_name);
    moveExpenseButton = (Button) findViewById(R.id.btn_move_expense);
    // Retrieve data of this pending expense
    databaseReference.child("proposedExpenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            expenseName = dataSnapshot.child("description").getValue(String.class);
            String groupName = dataSnapshot.child("groupName").getValue(String.class);
            Double amount = dataSnapshot.child("amount").getValue(Double.class);
            expenseNameTextView.setText(expenseName);
            groupTextView.setText(groupName);
            amountTextView.setText(amount.toString());
            creatorID = dataSnapshot.child("creatorID").getValue(String.class);
            groupID = dataSnapshot.child("groupID").getValue(String.class);
            // .load(dataSnapshot.child("image").getValue(String.class))
            Glide.with(getApplicationContext()).load(dataSnapshot.child("expensePhoto").getValue(String.class)).placeholder(R.color.colorPrimary).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
            databaseReference.child("users").child(creatorID).addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot creatorSnapshot) {
                    creatorNameTextView.setText(creatorSnapshot.child("name").getValue(String.class) + " " + creatorSnapshot.child("surname").getValue(String.class));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
            DecimalFormat df = new DecimalFormat("#.##");
            amountTextView.setText(df.format(amount) + " €");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    // Click on button to move from pending to real expense
    moveExpenseButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Only the creator of pending expense can move it
            if (creatorID.equals(userID)) {
                databaseReference.child("proposedExpenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        ArrayList<String> participants = new ArrayList<String>();
                        expenseName = dataSnapshot.child("description").getValue(String.class);
                        groupID = dataSnapshot.child("groupID").getValue(String.class);
                        Double amount = dataSnapshot.child("amount").getValue(Double.class);
                        String currency = dataSnapshot.child("currency").getValue(String.class);
                        String creatorID = dataSnapshot.child("creatorID").getValue(String.class);
                        String expensePhoto = dataSnapshot.child("expensePhoto").getValue(String.class);
                        for (DataSnapshot participantSnap : dataSnapshot.child("participants").getChildren()) participants.add(participantSnap.getKey());
                        Expense newExpense = new Expense();
                        newExpense.setDescription(expenseName);
                        newExpense.setAmount(amount);
                        newExpense.setCurrency(currency);
                        newExpense.setGroupID(groupID);
                        newExpense.setCreatorID(creatorID);
                        newExpense.setEquallyDivided(true);
                        newExpense.setDeleted(false);
                        newExpense.setExpensePhoto(expensePhoto);
                        Double amountPerMember = 1 / (double) participants.size();
                        for (String participant : participants) {
                            newExpense.getParticipants().put(participant, amountPerMember);
                            // Delete expense from his proposed expenses
                            databaseReference.child("users").child(participant).child("proposedExpenses").child(expenseID).setValue(false);
                        }
                        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
                        newExpense.setTimestamp(timeStamp);
                        // Add expense to db
                        FirebaseUtils.getInstance().addExpenseFirebase(newExpense, null, null, getApplicationContext());
                        // Delete pending expense from proposed expenses list
                        databaseReference.child("proposedExpenses").child(expenseID).child("deleted").setValue(true);
                        // Delete pending expense from group
                        databaseReference.child("groups").child(groupID).child("proposedExpenses").child(expenseID).setValue(false);
                        // add event for PENDING_EXPENSE_APPROVED
                        User currentUser = MainActivity.getCurrentUser();
                        String userID = currentUser.getID();
                        Event event = new Event(groupID, Event.EventType.PENDING_EXPENSE_APPROVED, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
                        event.setDate(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date()));
                        event.setTime(new SimpleDateFormat("HH:mm").format(new java.util.Date()));
                        FirebaseUtils.getInstance().addEvent(event);
                        Intent myIntent = new Intent(PendingExpenseDetailActivity.this, GroupDetailActivity.class);
                        myIntent.putExtra("groupID", groupID);
                        myIntent.putExtra("userID", userID);
                        finish();
                        startActivity(myIntent);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            } else {
                Toast.makeText(PendingExpenseDetailActivity.this, getString(R.string.only_creator), Toast.LENGTH_SHORT).show();
                return;
            }
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) DataSnapshot(com.google.firebase.database.DataSnapshot) Expense(com.polito.mad17.madmax.entities.Expense) TabLayout(android.support.design.widget.TabLayout) ValueEventListener(com.google.firebase.database.ValueEventListener) ActionBar(android.support.v7.app.ActionBar) ExpenseDetailPagerAdapter(com.polito.mad17.madmax.activities.ExpenseDetailPagerAdapter) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) DatabaseError(com.google.firebase.database.DatabaseError) Event(com.polito.mad17.madmax.entities.Event) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

TabLayout (android.support.design.widget.TabLayout)82 View (android.view.View)36 ViewPager (android.support.v4.view.ViewPager)31 Toolbar (android.support.v7.widget.Toolbar)19 Intent (android.content.Intent)16 TextView (android.widget.TextView)15 ActionBar (android.support.v7.app.ActionBar)12 RecyclerView (android.support.v7.widget.RecyclerView)12 ImageView (android.widget.ImageView)11 Fragment (android.support.v4.app.Fragment)10 NavigationView (android.support.design.widget.NavigationView)8 Test (org.junit.Test)8 Bundle (android.os.Bundle)7 FloatingActionButton (android.support.design.widget.FloatingActionButton)7 UiController (android.support.test.espresso.UiController)7 ViewAction (android.support.test.espresso.ViewAction)7 ViewGroup (android.view.ViewGroup)7 AppBarLayout (android.support.design.widget.AppBarLayout)6 MenuItem (android.view.MenuItem)6 FragmentPagerAdapter (android.support.v4.app.FragmentPagerAdapter)5