Example usage for android.widget FrameLayout FrameLayout

List of usage examples for android.widget FrameLayout FrameLayout

Introduction

In this page you can find the example usage for android.widget FrameLayout FrameLayout.

Prototype

public FrameLayout(@NonNull Context context) 

Source Link

Usage

From source file:com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock2ViewHolder.java

private void setupYoutube(final ContentBlock contentBlock) {
    final String youtubeVideoId = getYoutubeVideoId(contentBlock.getVideoUrl());

    Bitmap savedBitmap = mBitmapCache.get(youtubeVideoId);
    if (savedBitmap != null) {
        mProgressBar.setVisibility(View.GONE);
        mYouTubeThumbnailView.setImageBitmap(savedBitmap);
    } else {//from  w w  w .  ja  v a  2 s.co m
        mYouTubeThumbnailView.initialize(mYoutubeApiKey, new YouTubeThumbnailView.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView,
                    final YouTubeThumbnailLoader youTubeThumbnailLoader) {
                youTubeThumbnailLoader.setVideo(youtubeVideoId);
                youTubeThumbnailLoader
                        .setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
                            @Override
                            public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                                mProgressBar.setVisibility(View.GONE);

                                Drawable drawable = mYouTubeThumbnailView.getDrawable();
                                if (drawable instanceof BitmapDrawable) {
                                    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
                                    mBitmapCache.put(youtubeVideoId, bitmapDrawable.getBitmap());
                                }
                                youTubeThumbnailLoader.release();
                            }

                            @Override
                            public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView,
                                    YouTubeThumbnailLoader.ErrorReason errorReason) {
                                youTubeThumbnailView.setBackgroundColor(Color.BLACK);
                                mProgressBar.setVisibility(View.GONE);
                                youtubeFallback(contentBlock.getVideoUrl());
                                youTubeThumbnailLoader.release();
                            }
                        });
            }

            @Override
            public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView,
                    YouTubeInitializationResult youTubeInitializationResult) {
                mProgressBar.setVisibility(View.GONE);
                mVideoPlayImageView.setVisibility(View.GONE);
                youtubeFallback(contentBlock.getVideoUrl());
            }
        });
    }

    mYouTubeThumbnailView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendResetYoutubeBroadcast();
            LocalBroadcastManager.getInstance(mContext).registerReceiver(mResetYoutubeBroadCastReciever,
                    new IntentFilter(RESET_YOUTUBE));

            mVideoPlayImageView.setVisibility(View.GONE);

            final FrameLayout frame = new FrameLayout(mContext);
            frame.setId(R.id.youtube_fragment_id);

            FrameLayout.LayoutParams layoutParams = layoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            frame.setLayoutParams(layoutParams);

            mFramelayout.addView(frame);

            final YouTubePlayerSupportFragment youTubePlayerSupportFragment = YouTubePlayerSupportFragment
                    .newInstance();
            mFragment.getChildFragmentManager().beginTransaction()
                    .add(frame.getId(), youTubePlayerSupportFragment).commit();

            youTubePlayerSupportFragment.initialize(mYoutubeApiKey, new YouTubePlayer.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubePlayer.Provider provider,
                        final YouTubePlayer youTubePlayer, boolean b) {
                    youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);

                    youTubePlayer.loadVideo(youtubeVideoId);
                    mProgressBar.setVisibility(View.GONE);

                    youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
                        @Override
                        public void onFullscreen(boolean enterFullscreen) {
                            if (enterFullscreen) {
                                Intent intent = YouTubeStandalonePlayer.createVideoIntent(
                                        mFragment.getActivity(), mYoutubeApiKey, youtubeVideoId,
                                        youTubePlayer.getCurrentTimeMillis(), true, false);
                                mFragment.getActivity().startActivity(intent);
                            }
                        }
                    });
                }

                @Override
                public void onInitializationFailure(YouTubePlayer.Provider provider,
                        YouTubeInitializationResult youTubeInitializationResult) {
                    mProgressBar.setVisibility(View.GONE);
                    youtubeFallback(contentBlock.getVideoUrl());
                    Log.e("tag", youTubeInitializationResult.toString());
                }
            });
        }
    });
}

From source file:org.cafemember.ui.LaunchActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Date now = new Date();
    /*int year = now.getYear();
    int month = now.getMonth();/*from   w  w  w  .jav  a  2  s . c om*/
    int day = now.getDay();
    now.getDate();
    long curr = 147083220000l;
    if(System.currentTimeMillis() > curr ){
    Toast.makeText(this,"    . ?      ",Toast.LENGTH_LONG).show();
    finish();
    }*/

    ApplicationLoader.postInitApplication();
    NativeCrashManager.handleDumpFiles(this);

    if (!UserConfig.isClientActivated()) {
        Intent intent = getIntent();
        if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction())
                || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
            super.onCreate(savedInstanceState);
            finish();
            return;
        }
        if (intent != null && !intent.getBooleanExtra("fromIntro", false)) {
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("logininfo2", MODE_PRIVATE);
            Map<String, ?> state = preferences.getAll();
            if (state.isEmpty()) {
                Intent intent2 = new Intent(this, IntroActivity.class);
                startActivity(intent2);
                super.onCreate(savedInstanceState);
                finish();
                return;
            }
        }
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setTheme(R.style.Theme_TMessages);
    getWindow().setBackgroundDrawableResource(R.drawable.transparent);

    super.onCreate(savedInstanceState);
    Theme.loadRecources(this);

    if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
        UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
    }

    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }

    actionBarLayout = new ActionBarLayout(this);

    drawerLayoutContainer = new DrawerLayoutContainer(this);
    setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));

    if (AndroidUtilities.isTablet()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        RelativeLayout launchLayout = new RelativeLayout(this);
        drawerLayoutContainer.addView(launchLayout);
        FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) launchLayout.getLayoutParams();
        layoutParams1.width = LayoutHelper.MATCH_PARENT;
        layoutParams1.height = LayoutHelper.MATCH_PARENT;
        launchLayout.setLayoutParams(layoutParams1);

        backgroundTablet = new ImageView(this);
        backgroundTablet.setScaleType(ImageView.ScaleType.CENTER_CROP);
        backgroundTablet.setImageResource(R.drawable.cats);
        launchLayout.addView(backgroundTablet);
        RelativeLayout.LayoutParams relativeLayoutParams = (RelativeLayout.LayoutParams) backgroundTablet
                .getLayoutParams();
        relativeLayoutParams.width = LayoutHelper.MATCH_PARENT;
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        backgroundTablet.setLayoutParams(relativeLayoutParams);

        launchLayout.addView(actionBarLayout);
        relativeLayoutParams = (RelativeLayout.LayoutParams) actionBarLayout.getLayoutParams();
        relativeLayoutParams.width = LayoutHelper.MATCH_PARENT;
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        actionBarLayout.setLayoutParams(relativeLayoutParams);

        rightActionBarLayout = new ActionBarLayout(this);
        launchLayout.addView(rightActionBarLayout);
        relativeLayoutParams = (RelativeLayout.LayoutParams) rightActionBarLayout.getLayoutParams();
        relativeLayoutParams.width = AndroidUtilities.dp(320);
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        rightActionBarLayout.setLayoutParams(relativeLayoutParams);
        rightActionBarLayout.init(rightFragmentsStack);
        rightActionBarLayout.setDelegate(this);

        shadowTabletSide = new FrameLayout(this);
        shadowTabletSide.setBackgroundColor(0x40295274);
        launchLayout.addView(shadowTabletSide);
        relativeLayoutParams = (RelativeLayout.LayoutParams) shadowTabletSide.getLayoutParams();
        relativeLayoutParams.width = AndroidUtilities.dp(1);
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        shadowTabletSide.setLayoutParams(relativeLayoutParams);

        shadowTablet = new FrameLayout(this);
        shadowTablet.setVisibility(View.GONE);
        shadowTablet.setBackgroundColor(0x7F000000);
        launchLayout.addView(shadowTablet);
        relativeLayoutParams = (RelativeLayout.LayoutParams) shadowTablet.getLayoutParams();
        relativeLayoutParams.width = LayoutHelper.MATCH_PARENT;
        relativeLayoutParams.height = LayoutHelper.MATCH_PARENT;
        shadowTablet.setLayoutParams(relativeLayoutParams);
        shadowTablet.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
                    float x = event.getX();
                    float y = event.getY();
                    int location[] = new int[2];
                    layersActionBarLayout.getLocationOnScreen(location);
                    int viewX = location[0];
                    int viewY = location[1];

                    if (layersActionBarLayout.checkTransitionAnimation()
                            || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY
                                    && y < viewY + layersActionBarLayout.getHeight()) {
                        return false;
                    } else {
                        if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
                            for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
                                layersActionBarLayout
                                        .removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
                                a--;
                            }
                            layersActionBarLayout.closeLastFragment(true);
                        }
                        return true;
                    }
                }
                return false;
            }
        });

        shadowTablet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        layersActionBarLayout = new ActionBarLayout(this);
        layersActionBarLayout.setRemoveActionBarExtraHeight(true);
        layersActionBarLayout.setBackgroundView(shadowTablet);
        layersActionBarLayout.setUseAlphaAnimations(true);
        layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
        launchLayout.addView(layersActionBarLayout);
        relativeLayoutParams = (RelativeLayout.LayoutParams) layersActionBarLayout.getLayoutParams();
        relativeLayoutParams.width = AndroidUtilities.dp(530);
        relativeLayoutParams.height = AndroidUtilities.dp(528);
        layersActionBarLayout.setLayoutParams(relativeLayoutParams);
        layersActionBarLayout.init(layerFragmentsStack);
        layersActionBarLayout.setDelegate(this);
        layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
        layersActionBarLayout.setVisibility(View.GONE);
    } else {
        drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    ListView listView = new ListView(this) {
        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }
    };
    listView.setBackgroundColor(0xffffffff);
    listView.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
    listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    drawerLayoutContainer.setDrawerLayout(listView);
    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
    Point screenSize = AndroidUtilities.getRealScreenSize();
    layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320)
            : Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56);
    layoutParams.height = LayoutHelper.MATCH_PARENT;
    listView.setLayoutParams(layoutParams);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //
            if (position == 12) {
                presentFragment(new SettingsActivity());
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 11) {

                try {
                    RulesActivity his = new RulesActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 2) {

                Defaults def = Defaults.getInstance();
                boolean open = def.openOnJoin();
                def.setOpenOnJoin(!open);
                if (view instanceof TextCheckCell) {
                    ((TextCheckCell) view).setChecked(!open);
                }
            } else if (position == 4) {
                try {
                    HistoryActivity his = new HistoryActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            }

            else if (position == 3) {
                Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://telegram.me/cafemember"));
                startActivity(telegram);

                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 5) {
                try {
                    FAQActivity his = new FAQActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 6) {
                Intent telegram = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https://telegram.me/" + Defaults.getInstance().getSupport()));
                startActivity(telegram);

                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 7) {
                try {
                    HelpActivity his = new HelpActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 8) {
                try {
                    AddRefActivity his = new AddRefActivity();
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 9) {

                try {
                    Log.d("TAB", "Triggering");
                    ShareActivity his = new ShareActivity();
                    Log.d("TAB", "Triggered");
                    presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            } else if (position == 10) {
                try {
                    //                        TransfareActivity his = new TransfareActivity();
                    //                        presentFragment(his);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                drawerLayoutContainer.closeDrawer(false);
            }
        }
    });

    drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
    actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
    actionBarLayout.init(mainFragmentsStack);
    actionBarLayout.setDelegate(this);

    ApplicationLoader.loadWallpaper();

    passcodeView = new PasscodeView(this);
    drawerLayoutContainer.addView(passcodeView);
    FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) passcodeView.getLayoutParams();
    layoutParams1.width = LayoutHelper.MATCH_PARENT;
    layoutParams1.height = LayoutHelper.MATCH_PARENT;
    passcodeView.setLayoutParams(layoutParams1);

    NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
    currentConnectionState = ConnectionsManager.getInstance().getConnectionState();

    NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
    if (Build.VERSION.SDK_INT < 14) {
        NotificationCenter.getInstance().addObserver(this, NotificationCenter.screenStateChanged);
    }

    if (actionBarLayout.fragmentsStack.isEmpty()) {
        if (!UserConfig.isClientActivated()) {
            actionBarLayout.addFragmentToStack(new LoginActivity());
            drawerLayoutContainer.setAllowOpenDrawer(false, false);
        } else {
            dialogsFragment = new DialogsActivity(null);
            actionBarLayout.addFragmentToStack(dialogsFragment);
            drawerLayoutContainer.setAllowOpenDrawer(true, false);
        }

        try {
            if (savedInstanceState != null) {
                String fragmentName = savedInstanceState.getString("fragment");
                if (fragmentName != null) {
                    Bundle args = savedInstanceState.getBundle("args");
                    switch (fragmentName) {
                    case "chat":
                        if (args != null) {
                            ChatActivity chat = new ChatActivity(args);
                            if (actionBarLayout.addFragmentToStack(chat)) {
                                chat.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "settings": {
                        SettingsActivity settings = new SettingsActivity();
                        actionBarLayout.addFragmentToStack(settings);
                        settings.restoreSelfArgs(savedInstanceState);
                        break;
                    }
                    case "group":
                        if (args != null) {
                            GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
                            if (actionBarLayout.addFragmentToStack(group)) {
                                group.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "channel":
                        if (args != null) {
                            ChannelCreateActivity channel = new ChannelCreateActivity(args);
                            if (actionBarLayout.addFragmentToStack(channel)) {
                                channel.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "edit":
                        if (args != null) {
                            ChannelEditActivity channel = new ChannelEditActivity(args);
                            if (actionBarLayout.addFragmentToStack(channel)) {
                                channel.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "chat_profile":
                        if (args != null) {
                            ProfileActivity profile = new ProfileActivity(args);
                            if (actionBarLayout.addFragmentToStack(profile)) {
                                profile.restoreSelfArgs(savedInstanceState);
                            }
                        }
                        break;
                    case "wallpapers": {
                        WallpapersActivity settings = new WallpapersActivity();
                        actionBarLayout.addFragmentToStack(settings);
                        settings.restoreSelfArgs(savedInstanceState);
                        break;
                    }
                    }
                }
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    } else {
        boolean allowOpen = true;
        if (AndroidUtilities.isTablet()) {
            allowOpen = actionBarLayout.fragmentsStack.size() <= 1
                    && layersActionBarLayout.fragmentsStack.isEmpty();
            if (layersActionBarLayout.fragmentsStack.size() == 1
                    && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
                allowOpen = false;
            }
        }
        if (actionBarLayout.fragmentsStack.size() == 1
                && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
            allowOpen = false;
        }
        drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
    }

    handleIntent(getIntent(), false, savedInstanceState != null, false);
    needLayout();

    final View view = getWindow().getDecorView().getRootView();
    view.getViewTreeObserver()
            .addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int height = view.getMeasuredHeight();
                    if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y
                            && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
                        AndroidUtilities.displaySize.y = height;
                        FileLog.e("tmessages", "fix display size y to " + AndroidUtilities.displaySize.y);
                    }
                }
            });
}

From source file:com.vaporwarecorp.mirror.component.dottedgrid.DottedGridView.java

private void initializeLayout(Context context) {
    mViews = new LinkedHashSet<>();

    FrameLayout gridLayout = new FrameLayout(context);
    gridLayout.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_dotted_grid));
    gridLayout.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));

    mBackground = new FrameLayout(context);
    mBackground.addView(gridLayout);/*from  w  w  w.  ja  va2 s.com*/
    mBackground.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));
    mBackground.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_solid_border));
    mBackground.setVisibility(INVISIBLE);
    addView(mBackground);

    // now set the child clipping to false
    setClipChildren(false);
}

From source file:org.zywx.wbpalmstar.engine.universalex.EUExBase.java

/**
 * viewid/* www  .j  a va2s.  co m*/
 *
 * @param child
 * @param index
 * @param opid
 */
public final void addSubviewToContainer(final View child, final int index, final String opid,
        final FrameLayout.LayoutParams parms) {
    if (null == mBrwView || opid == null || index < 0 || parms == null) {
        return;
    }
    ((EBrowserActivity) mContext).runOnUiThread(new Runnable() {

        @Override
        public void run() {
            EBrowserWindow mWindow = mBrwView.getBrowserWindow();
            int count = mWindow.getChildCount();
            int l = (int) (parms.leftMargin);
            int t = (int) (parms.topMargin);
            int w = parms.width;
            int h = parms.height;
            for (int i = 0; i < count; i++) {
                View view = mWindow.getChildAt(i);
                if (view instanceof ContainerViewPager) {
                    final ContainerViewPager pager = (ContainerViewPager) view;
                    if (opid.equals(pager.getContainerVO().getId())) {
                        ContainerAdapter adapter = (ContainerAdapter) pager.getAdapter();
                        Vector<FrameLayout> views = adapter.getViewList();
                        boolean needAnim = views.size() == 0;//view
                        child.setLayoutParams(parms);
                        FrameLayout layout = new FrameLayout(mContext);
                        layout.addView(child);
                        if (views.size() <= index) {
                            for (int j = views.size(); j <= index; j++) {
                                if (j == index) {
                                    views.add(layout);
                                } else {
                                    views.add(new FrameLayout(mContext));
                                }
                            }
                        } else {
                            views.set(index, layout);
                        }
                        adapter.setViewList(views);
                        adapter.notifyDataSetChanged();
                        if (needAnim && pager.getContainerVO().getAnimTime() != 0) {
                            startAnimationDelay(pager, child);
                        }
                        return;
                    } //end equals opid
                } //end instanceof
            } //end for
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(w, h);
            lp.leftMargin = l;
            lp.topMargin = t;
            addViewToCurrentWindow(child, lp);
        }// end run 
    });// end runOnUI
}

From source file:org.telegram.ui.SettingsActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_avatar_actionBarSelectorBlue), false);
    actionBar.setItemsColor(Theme.getColor(Theme.key_avatar_actionBarIconBlue), false);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAddToContainer(false);/*from w w w  .  java  2s  . c o m*/
    extraHeight = 88;
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == edit_name) {
                presentFragment(new ChangeNameActivity());
            } else if (id == logout) {
                presentFragment(new LogoutActivity());
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
    item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName));
    item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut));

    int scrollTo;
    int scrollToPosition = 0;
    Object writeButtonTag = null;
    if (listView != null) {
        scrollTo = layoutManager.findFirstVisibleItemPosition();
        View topView = layoutManager.findViewByPosition(scrollTo);
        if (topView != null) {
            scrollToPosition = topView.getTop();
        } else {
            scrollTo = -1;
        }
        writeButtonTag = writeButton.getTag();
    } else {
        scrollTo = -1;
    }

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context) {
        @Override
        protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
            if (child == listView) {
                boolean result = super.drawChild(canvas, child, drawingTime);
                if (parentLayout != null) {
                    int actionBarHeight = 0;
                    int childCount = getChildCount();
                    for (int a = 0; a < childCount; a++) {
                        View view = getChildAt(a);
                        if (view == child) {
                            continue;
                        }
                        if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
                            if (((ActionBar) view).getCastShadows()) {
                                actionBarHeight = view.getMeasuredHeight();
                            }
                            break;
                        }
                    }
                    parentLayout.drawHeaderShadow(canvas, actionBarHeight);
                }
                return result;
            } else {
                return super.drawChild(canvas, child, drawingTime);
            }
        }
    };
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    FrameLayout frameLayout = (FrameLayout) fragmentView;

    listView = new RecyclerListView(context);
    listView.setVerticalScrollBarEnabled(false);
    listView.setLayoutManager(
            layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {
                @Override
                public boolean supportsPredictiveItemAnimations() {
                    return false;
                }
            });
    listView.setGlowColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.TOP | Gravity.LEFT));
    listView.setAdapter(listAdapter);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setOnItemClickListener((view, position) -> {
        if (position == notificationRow) {
            presentFragment(new NotificationsSettingsActivity());
        } else if (position == privacyRow) {
            presentFragment(new PrivacySettingsActivity());
        } else if (position == dataRow) {
            presentFragment(new DataSettingsActivity());
        } else if (position == chatRow) {
            presentFragment(new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC));
        } else if (position == helpRow) {
            BottomSheet.Builder builder = new BottomSheet.Builder(context);
            builder.setApplyTopPadding(false);

            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);

            HeaderCell headerCell = new HeaderCell(context, true, 23, 15, false);
            headerCell.setHeight(47);
            headerCell.setText(LocaleController.getString("SettingsHelp", R.string.SettingsHelp));
            linearLayout.addView(headerCell);

            LinearLayout linearLayoutInviteContainer = new LinearLayout(context);
            linearLayoutInviteContainer.setOrientation(LinearLayout.VERTICAL);
            linearLayout.addView(linearLayoutInviteContainer,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

            int count = 6;
            for (int a = 0; a < count; a++) {
                if (a >= 3 && a <= 4 && !BuildVars.LOGS_ENABLED || a == 5 && !BuildVars.DEBUG_VERSION) {
                    continue;
                }
                TextCell textCell = new TextCell(context);
                String text;
                switch (a) {
                case 0:
                    text = LocaleController.getString("AskAQuestion", R.string.AskAQuestion);
                    break;
                case 1:
                    text = LocaleController.getString("TelegramFAQ", R.string.TelegramFAQ);
                    break;
                case 2:
                    text = LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy);
                    break;
                case 3:
                    text = LocaleController.getString("DebugSendLogs", R.string.DebugSendLogs);
                    break;
                case 4:
                    text = LocaleController.getString("DebugClearLogs", R.string.DebugClearLogs);
                    break;
                case 5:
                default:
                    text = "Switch Backend";
                    break;
                }
                textCell.setText(text,
                        BuildVars.LOGS_ENABLED || BuildVars.DEBUG_VERSION ? a != count - 1 : a != 2);
                textCell.setTag(a);
                textCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                linearLayoutInviteContainer.addView(textCell,
                        LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                textCell.setOnClickListener(v2 -> {
                    Integer tag = (Integer) v2.getTag();
                    switch (tag) {
                    case 0: {
                        showDialog(AlertsCreator.createSupportAlert(SettingsActivity.this));
                        break;
                    }
                    case 1:
                        Browser.openUrl(getParentActivity(),
                                LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
                        break;
                    case 2:
                        Browser.openUrl(getParentActivity(),
                                LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl));
                        break;
                    case 3:
                        sendLogs();
                        break;
                    case 4:
                        FileLog.cleanupLogs();
                        break;
                    case 5: {
                        if (getParentActivity() == null) {
                            return;
                        }
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
                        builder1.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
                        builder1.setTitle(LocaleController.getString("AppName", R.string.AppName));
                        builder1.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                (dialogInterface, i) -> {
                                    SharedConfig.pushAuthKey = null;
                                    SharedConfig.pushAuthKeyId = null;
                                    SharedConfig.saveConfig();
                                    ConnectionsManager.getInstance(currentAccount).switchBackend();
                                });
                        builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                        showDialog(builder1.create());
                        break;
                    }
                    }
                    builder.getDismissRunnable().run();
                });
            }
            builder.setCustomView(linearLayout);
            showDialog(builder.create());
        } else if (position == languageRow) {
            presentFragment(new LanguageSelectActivity());
        } else if (position == usernameRow) {
            presentFragment(new ChangeUsernameActivity());
        } else if (position == bioRow) {
            if (userInfo != null) {
                presentFragment(new ChangeBioActivity());
            }
        } else if (position == numberRow) {
            presentFragment(new ChangePhoneHelpActivity());
        }
    });

    listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {

        private int pressCount = 0;

        @Override
        public boolean onItemClick(View view, int position) {
            if (position == versionRow) {
                pressCount++;
                if (pressCount >= 2 || BuildVars.DEBUG_PRIVATE_VERSION) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("DebugMenu", R.string.DebugMenu));
                    CharSequence[] items;
                    items = new CharSequence[] {
                            LocaleController.getString("DebugMenuImportContacts",
                                    R.string.DebugMenuImportContacts),
                            LocaleController.getString("DebugMenuReloadContacts",
                                    R.string.DebugMenuReloadContacts),
                            LocaleController.getString("DebugMenuResetContacts",
                                    R.string.DebugMenuResetContacts),
                            LocaleController.getString("DebugMenuResetDialogs", R.string.DebugMenuResetDialogs),
                            BuildVars.LOGS_ENABLED
                                    ? LocaleController.getString("DebugMenuDisableLogs",
                                            R.string.DebugMenuDisableLogs)
                                    : LocaleController.getString("DebugMenuEnableLogs",
                                            R.string.DebugMenuEnableLogs),
                            SharedConfig.inappCamera
                                    ? LocaleController.getString("DebugMenuDisableCamera",
                                            R.string.DebugMenuDisableCamera)
                                    : LocaleController.getString("DebugMenuEnableCamera",
                                            R.string.DebugMenuEnableCamera),
                            LocaleController.getString("DebugMenuClearMediaCache",
                                    R.string.DebugMenuClearMediaCache),
                            LocaleController.getString("DebugMenuCallSettings", R.string.DebugMenuCallSettings),
                            null, BuildVars.DEBUG_PRIVATE_VERSION ? "Check for app updates" : null };
                    builder.setItems(items, (dialog, which) -> {
                        if (which == 0) {
                            UserConfig.getInstance(currentAccount).syncContacts = true;
                            UserConfig.getInstance(currentAccount).saveConfig(false);
                            ContactsController.getInstance(currentAccount).forceImportContacts();
                        } else if (which == 1) {
                            ContactsController.getInstance(currentAccount).loadContacts(false, 0);
                        } else if (which == 2) {
                            ContactsController.getInstance(currentAccount).resetImportedContacts();
                        } else if (which == 3) {
                            MessagesController.getInstance(currentAccount).forceResetDialogs();
                        } else if (which == 4) {
                            BuildVars.LOGS_ENABLED = !BuildVars.LOGS_ENABLED;
                            SharedPreferences sharedPreferences = ApplicationLoader.applicationContext
                                    .getSharedPreferences("systemConfig", Context.MODE_PRIVATE);
                            sharedPreferences.edit().putBoolean("logsEnabled", BuildVars.LOGS_ENABLED).commit();
                        } else if (which == 5) {
                            SharedConfig.toggleInappCamera();
                        } else if (which == 6) {
                            MessagesStorage.getInstance(currentAccount).clearSentMedia();
                            SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit();
                            SharedConfig.setNoSoundHintShowed(false);
                        } else if (which == 7) {
                            VoIPHelper.showCallDebugSettings(getParentActivity());
                        } else if (which == 8) {
                            SharedConfig.toggleRoundCamera16to9();
                        } else if (which == 9) {
                            ((LaunchActivity) getParentActivity()).checkAppUpdate(true);
                        }
                    });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    try {
                        Toast.makeText(getParentActivity(), "\\_()_/", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            }
            return false;
        }
    });

    frameLayout.addView(actionBar);

    extraHeightView = new View(context);
    extraHeightView.setPivotY(0);
    extraHeightView.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88));

    shadowView = new View(context);
    shadowView.setBackgroundResource(R.drawable.header_shadow);
    frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));

    avatarContainer = new FrameLayout(context);
    avatarContainer.setPivotX(LocaleController.isRTL ? AndroidUtilities.dp(42) : 0);
    avatarContainer.setPivotY(0);
    frameLayout.addView(avatarContainer,
            LayoutHelper.createFrame(42, 42,
                    Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                    (LocaleController.isRTL ? 0 : 64), 0, (LocaleController.isRTL ? 64 : 0), 0));
    avatarContainer.setOnClickListener(v -> {
        if (avatar != null) {
            return;
        }
        TLRPC.User user = MessagesController.getInstance(currentAccount)
                .getUser(UserConfig.getInstance(currentAccount).getClientUserId());
        if (user != null && user.photo != null && user.photo.photo_big != null) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(user.photo.photo_big, provider);
        }
    });

    avatarImage = new BackupImageView(context);
    avatarImage.setRoundRadius(AndroidUtilities.dp(21));
    avatarContainer.addView(avatarImage, LayoutHelper.createFrame(42, 42));

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(0x55000000);

    avatarProgressView = new RadialProgressView(context) {
        @Override
        protected void onDraw(Canvas canvas) {
            if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) {
                paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha()));
                canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, AndroidUtilities.dp(21),
                        paint);
            }
            super.onDraw(canvas);
        }
    };
    avatarProgressView.setSize(AndroidUtilities.dp(26));
    avatarProgressView.setProgressColor(0xffffffff);
    avatarContainer.addView(avatarProgressView, LayoutHelper.createFrame(42, 42));

    showAvatarProgress(false, false);

    nameTextView = new TextView(context) {
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            setPivotX(LocaleController.isRTL ? getMeasuredWidth() : 0);
        }
    };
    nameTextView.setTextColor(Theme.getColor(Theme.key_profile_title));
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    nameTextView.setLines(1);
    nameTextView.setMaxLines(1);
    nameTextView.setSingleLine(true);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setPivotY(0);
    frameLayout.addView(nameTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0));

    onlineTextView = new TextView(context);
    onlineTextView.setTextColor(Theme.getColor(Theme.key_avatar_subtitleInProfileBlue));
    onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    onlineTextView.setLines(1);
    onlineTextView.setMaxLines(1);
    onlineTextView.setSingleLine(true);
    onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
    onlineTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    frameLayout.addView(onlineTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0));

    writeButton = new ImageView(context);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56),
            Theme.getColor(Theme.key_profile_actionBackground),
            Theme.getColor(Theme.key_profile_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile)
                .mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    writeButton.setBackgroundDrawable(drawable);
    writeButton.setImageResource(R.drawable.menu_camera_av);
    writeButton.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_profile_actionIcon), PorterDuff.Mode.MULTIPLY));
    writeButton.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed },
                ObjectAnimator
                        .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4))
                        .setDuration(200));
        animator.addState(new int[] {},
                ObjectAnimator
                        .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2))
                        .setDuration(200));
        writeButton.setStateListAnimator(animator);
        writeButton.setOutlineProvider(new ViewOutlineProvider() {
            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    frameLayout.addView(writeButton,
            LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                    Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                    (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP,
                    LocaleController.isRTL ? 16 : 0, 0, LocaleController.isRTL ? 0 : 16, 0));
    writeButton.setOnClickListener(v -> {
        TLRPC.User user = MessagesController.getInstance(currentAccount)
                .getUser(UserConfig.getInstance(currentAccount).getClientUserId());
        if (user == null) {
            user = UserConfig.getInstance(currentAccount).getCurrentUser();
        }
        if (user == null) {
            return;
        }
        imageUpdater.openMenu(
                user.photo != null && user.photo.photo_big != null
                        && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty),
                () -> MessagesController.getInstance(currentAccount).deleteUserPhoto(null));
    });

    if (scrollTo != -1) {
        layoutManager.scrollToPositionWithOffset(scrollTo, scrollToPosition);

        if (writeButtonTag != null) {
            writeButton.setTag(0);
            writeButton.setScaleX(0.2f);
            writeButton.setScaleY(0.2f);
            writeButton.setAlpha(0.0f);
            writeButton.setVisibility(View.GONE);
        }
    }

    needLayout();

    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (layoutManager.getItemCount() == 0) {
                return;
            }
            int height = 0;
            View child = recyclerView.getChildAt(0);
            if (child != null) {
                if (layoutManager.findFirstVisibleItemPosition() == 0) {
                    height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0);
                }
                if (extraHeight != height) {
                    extraHeight = height;
                    needLayout();
                }
            }
        }
    });

    return fragmentView;
}

From source file:com.silentcircle.contacts.list.ScDefaultContactBrowseListFragment.java

/**
 * This method creates a pseudo user profile contact. When the returned query doesn't have
 * a profile, this methods creates 2 views that are inserted as headers to the listview:
 * 1. A header view with the "ME" title and the contacts count.
 * 2. A button that prompts the user to create a local profile
 *//*from www . jav  a  2  s .c o m*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addEmptyUserProfileHeader(LayoutInflater inflater) {

    ListView list = getListView();
    // Put a header with the "ME" name and a view for the number of contacts
    // The view is embedded in a frame view since you cannot change the visibility of a
    // view in a ListView without having a parent view.
    mProfileHeaderContainer = new FrameLayout(inflater.getContext());
    mProfileHeader = inflater.inflate(R.layout.user_profile_header, null, false);
    mCounterHeaderView = (TextView) mProfileHeader.findViewById(R.id.contacts_count);
    mProfileTitle = (TextView) mProfileHeader.findViewById(R.id.profile_title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        mProfileTitle.setAllCaps(true);

    mProfileHeaderContainer.addView(mProfileHeader);
    list.addHeaderView(mProfileHeaderContainer, null, false);

    // Add a selectable view with a message inviting the user to create a local profile
    mMessageContainer = new FrameLayout(inflater.getContext());
    mProfileMessage = (Button) inflater.inflate(R.layout.user_profile_button, null, false);
    mMessageContainer.addView(mProfileMessage);
    list.addHeaderView(mMessageContainer, null, true);

    mProfileMessage.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_INSERT, RawContacts.CONTENT_URI);
            intent.putExtra(ContactEditorFragment.INTENT_EXTRA_NEW_LOCAL_PROFILE, true);
            startActivity(intent);
        }
    });
}

From source file:uk.co.senab.photup.PhotoViewerActivity.java

private void showCaptionDialog() {
    final PhotoUpload currentUpload = getCurrentUpload();
    if (null != currentUpload) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.photo_caption);
        builder.setIcon(R.drawable.ic_action_caption);

        // Set an EditText view to get user input
        final FrameLayout layout = new FrameLayout(this);
        final int margin = getResources().getDimensionPixelSize(R.dimen.spacing);
        layout.setPadding(margin, margin, margin, margin);

        final EditText input = new EditText(this);
        input.setMinLines(2);//from  ww  w .  ja  v  a  2 s.  c  o  m
        input.setText(currentUpload.getCaption());
        layout.addView(input);

        builder.setView(layout);

        final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                switch (whichButton) {
                case AlertDialog.BUTTON_POSITIVE:
                    currentUpload.setCaption(input.getText().toString());
                    getSupportActionBar().setTitle(currentUpload.toString());
                    break;

                case AlertDialog.BUTTON_NEGATIVE:
                default:
                    dialog.dismiss();
                    break;
                }
            }
        };

        builder.setPositiveButton(android.R.string.ok, listener);
        builder.setNegativeButton(android.R.string.cancel, listener);
        builder.show();
    }
}

From source file:org.solovyev.android.messenger.BaseListFragment.java

@Nonnull
private View createListView() {
    final Context context = getThemeContext();

    final FrameLayout root = new FrameLayout(context);

    // ------------------------------------------------------------------

    final LinearLayout progressContainer = new LinearLayout(context);
    progressContainer.setId(INTERNAL_PROGRESS_CONTAINER_ID);
    progressContainer.setOrientation(VERTICAL);
    progressContainer.setVisibility(GONE);
    progressContainer.setGravity(CENTER);

    final ProgressBar progress = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge);
    progressContainer.addView(progress, new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

    root.addView(progressContainer, new LayoutParams(MATCH_PARENT, MATCH_PARENT));

    // ------------------------------------------------------------------

    final FrameLayout listViewContainer = new FrameLayout(context);
    listViewContainer.setId(INTERNAL_LIST_CONTAINER_ID);

    final TextView emptyListCaption = new TextView(context);
    emptyListCaption.setId(INTERNAL_EMPTY_ID);
    emptyListCaption.setGravity(CENTER);
    listViewContainer.addView(emptyListCaption, new LayoutParams(MATCH_PARENT, MATCH_PARENT));

    final ListViewAwareOnRefreshListener topRefreshListener = getTopPullRefreshListener();
    final ListViewAwareOnRefreshListener bottomRefreshListener = getBottomPullRefreshListener();

    final View listView;

    if (topRefreshListener == null && bottomRefreshListener == null) {
        pullToRefreshMode = null;/*  www  . j  ava  2 s. com*/
        listView = createListView(context);
    } else {
        listView = createPullToRefreshListView(context, topRefreshListener, bottomRefreshListener);
    }

    listViewContainer.addView(listView, new LayoutParams(MATCH_PARENT, MATCH_PARENT));

    root.addView(listViewContainer, new LayoutParams(MATCH_PARENT, MATCH_PARENT));

    // ------------------------------------------------------------------

    root.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));

    return root;
}

From source file:org.protocoderrunner.apprunner.AppRunnerFragment.java

public RelativeLayout initLayout() {
    LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

    // add main layout
    mainLayout = new RelativeLayout(mActivity);
    mainLayout.setLayoutParams(layoutParams);
    mainLayout.setGravity(Gravity.BOTTOM);
    // mainLayout.setBackgroundColor(getResources().getColor(R.color.transparent));
    mainLayout.setBackgroundColor(getResources().getColor(R.color.white));

    // set the parent
    parentScriptedLayout = new RelativeLayout(mActivity);
    parentScriptedLayout.setLayoutParams(layoutParams);
    parentScriptedLayout.setGravity(Gravity.BOTTOM);
    parentScriptedLayout.setBackgroundColor(getResources().getColor(R.color.transparent));
    mainLayout.addView(parentScriptedLayout);

    // editor layout
    editorLayout = new FrameLayout(mActivity);
    FrameLayout.LayoutParams editorParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);// w  w w  . ja  v a  2s  .c om
    editorLayout.setLayoutParams(editorParams);
    editorLayout.setId(EDITOR_ID);
    mainLayout.addView(editorLayout);

    // console layout
    consoleRLayout = new RelativeLayout(mActivity);
    RelativeLayout.LayoutParams consoleLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            getResources().getDimensionPixelSize(R.dimen.apprunner_console));
    consoleLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    consoleLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    consoleRLayout.setLayoutParams(consoleLayoutParams);
    consoleRLayout.setGravity(Gravity.BOTTOM);
    consoleRLayout.setBackgroundColor(getResources().getColor(R.color.blacktransparent));
    consoleRLayout.setVisibility(View.GONE);
    mainLayout.addView(consoleRLayout);

    // Create the text view to add to the console layout
    consoleText = new TextView(mActivity);
    LayoutParams consoleTextParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    consoleText.setBackgroundColor(getResources().getColor(R.color.transparent));
    consoleText.setTextColor(getResources().getColor(R.color.white));
    consoleText.setLayoutParams(consoleTextParams);
    int textPadding = getResources().getDimensionPixelSize(R.dimen.apprunner_console_text_padding);
    consoleText.setPadding(textPadding, textPadding, textPadding, textPadding);
    consoleRLayout.addView(consoleText);

    //add a close button
    Button closeBtn = new Button(mActivity);
    closeBtn.setText("x");
    closeBtn.setPadding(5, 5, 5, 5);
    closeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showConsole(false);
        }
    });
    RelativeLayout.LayoutParams closeBtnLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    closeBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    closeBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    closeBtn.setLayoutParams(closeBtnLayoutParams);
    consoleRLayout.addView(closeBtn);

    liveCoding = new PLiveCodingFeedback(mActivity);
    mainLayout.addView(liveCoding.add());

    return mainLayout;
}

From source file:org.telegram.ui.CacheControlActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("CacheSettings", R.string.CacheSettings));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/*  w w  w . ja v  a  2  s .  c  o  m*/
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    ListView listView = new ListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    listView.setDrawSelectorOnTop(true);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
            if (getParentActivity() == null) {
                return;
            }
            if (i == keepMediaRow) {
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setItems(
                        new CharSequence[] { LocaleController.formatPluralString("Weeks", 1),
                                LocaleController.formatPluralString("Months", 1),
                                LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever) },
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                SharedPreferences.Editor editor = ApplicationLoader.applicationContext
                                        .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
                                editor.putInt("keep_media", which).commit();
                                if (listAdapter != null) {
                                    listAdapter.notifyDataSetChanged();
                                }
                                PendingIntent pintent = PendingIntent.getService(
                                        ApplicationLoader.applicationContext, 0,
                                        new Intent(ApplicationLoader.applicationContext,
                                                ClearCacheService.class),
                                        0);
                                AlarmManager alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                                        .getSystemService(Context.ALARM_SERVICE);
                                if (which == 2) {
                                    alarmManager.cancel(pintent);
                                } else {
                                    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                            AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pintent);
                                }
                            }
                        });
                showDialog(builder.create());
            } else if (i == databaseRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setMessage(
                        LocaleController.getString("LocalDatabaseClear", R.string.LocalDatabaseClear));
                builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();
                                MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            SQLiteDatabase database = MessagesStorage.getInstance()
                                                    .getDatabase();
                                            ArrayList<Long> dialogsToCleanup = new ArrayList<>();
                                            SQLiteCursor cursor = database
                                                    .queryFinalized("SELECT did FROM dialogs WHERE 1");
                                            StringBuilder ids = new StringBuilder();
                                            while (cursor.next()) {
                                                long did = cursor.longValue(0);
                                                int lower_id = (int) did;
                                                int high_id = (int) (did >> 32);
                                                if (lower_id != 0 && high_id != 1) {
                                                    dialogsToCleanup.add(did);
                                                }
                                            }
                                            cursor.dispose();

                                            SQLitePreparedStatement state5 = database
                                                    .executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
                                            SQLitePreparedStatement state6 = database.executeFast(
                                                    "REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");

                                            database.beginTransaction();
                                            for (int a = 0; a < dialogsToCleanup.size(); a++) {
                                                Long did = dialogsToCleanup.get(a);
                                                int messagesCount = 0;
                                                cursor = database.queryFinalized(
                                                        "SELECT COUNT(mid) FROM messages WHERE uid = " + did);
                                                if (cursor.next()) {
                                                    messagesCount = cursor.intValue(0);
                                                }
                                                cursor.dispose();
                                                if (messagesCount <= 2) {
                                                    continue;
                                                }

                                                cursor = database.queryFinalized(
                                                        "SELECT last_mid_i, last_mid FROM dialogs WHERE did = "
                                                                + did);
                                                int messageId = -1;
                                                if (cursor.next()) {
                                                    long last_mid_i = cursor.longValue(0);
                                                    long last_mid = cursor.longValue(1);
                                                    SQLiteCursor cursor2 = database.queryFinalized(
                                                            "SELECT data FROM messages WHERE uid = " + did
                                                                    + " AND mid IN (" + last_mid_i + ","
                                                                    + last_mid + ")");
                                                    try {
                                                        while (cursor2.next()) {
                                                            NativeByteBuffer data = cursor2.byteBufferValue(0);
                                                            if (data != null) {
                                                                TLRPC.Message message = TLRPC.Message
                                                                        .TLdeserialize(data,
                                                                                data.readInt32(false), false);
                                                                data.reuse();
                                                                if (message != null) {
                                                                    messageId = message.id;
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    cursor2.dispose();

                                                    database.executeFast("DELETE FROM messages WHERE uid = "
                                                            + did + " AND mid != " + last_mid_i + " AND mid != "
                                                            + last_mid).stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM messages_holes WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM bot_keyboard WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_counts_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_holes_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    BotQuery.clearBotKeyboard(did, null);
                                                    if (messageId != -1) {
                                                        MessagesStorage.createFirstHoles(did, state5, state6,
                                                                messageId);
                                                    }
                                                }
                                                cursor.dispose();
                                            }
                                            state5.dispose();
                                            state6.dispose();
                                            database.commitTransaction();
                                            database.executeFast("VACUUM").stepThis().dispose();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        } finally {
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        progressDialog.dismiss();
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    if (listAdapter != null) {
                                                        File file = new File(
                                                                ApplicationLoader.getFilesDirFixed(),
                                                                "cache4.db");
                                                        databaseSize = file.length();
                                                        listAdapter.notifyDataSetChanged();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                showDialog(builder.create());
            } else if (i == cacheRow) {
                if (totalSize <= 0 || getParentActivity() == null) {
                    return;
                }
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setApplyTopPadding(false);
                builder.setApplyBottomPadding(false);
                LinearLayout linearLayout = new LinearLayout(getParentActivity());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                for (int a = 0; a < 6; a++) {
                    long size = 0;
                    String name = null;
                    if (a == 0) {
                        size = photoSize;
                        name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache);
                    } else if (a == 1) {
                        size = videoSize;
                        name = LocaleController.getString("LocalVideoCache", R.string.LocalVideoCache);
                    } else if (a == 2) {
                        size = documentsSize;
                        name = LocaleController.getString("LocalDocumentCache", R.string.LocalDocumentCache);
                    } else if (a == 3) {
                        size = musicSize;
                        name = LocaleController.getString("LocalMusicCache", R.string.LocalMusicCache);
                    } else if (a == 4) {
                        size = audioSize;
                        name = LocaleController.getString("LocalAudioCache", R.string.LocalAudioCache);
                    } else if (a == 5) {
                        size = cacheSize;
                        name = LocaleController.getString("LocalCache", R.string.LocalCache);
                    }
                    if (size > 0) {
                        clear[a] = true;
                        CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
                        checkBoxCell.setTag(a);
                        checkBoxCell.setBackgroundResource(R.drawable.list_selector);
                        linearLayout.addView(checkBoxCell,
                                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                        checkBoxCell.setText(name, AndroidUtilities.formatFileSize(size), true, true);
                        checkBoxCell.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CheckBoxCell cell = (CheckBoxCell) v;
                                int num = (Integer) cell.getTag();
                                clear[num] = !clear[num];
                                cell.setChecked(clear[num], true);
                            }
                        });
                    } else {
                        clear[a] = false;
                    }
                }
                BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
                cell.setBackgroundResource(R.drawable.list_selector);
                cell.setTextAndIcon(
                        LocaleController.getString("ClearMediaCache", R.string.ClearMediaCache).toUpperCase(),
                        0);
                cell.setTextColor(Theme.STICKERS_SHEET_REMOVE_TEXT_COLOR);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (visibleDialog != null) {
                                visibleDialog.dismiss();
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        cleanupFolders();
                    }
                });
                linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                builder.setCustomView(linearLayout);
                showDialog(builder.create());
            }
        }
    });

    return fragmentView;
}