Example usage for android.widget ProgressBar setIndeterminate

List of usage examples for android.widget ProgressBar setIndeterminate

Introduction

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

Prototype

@android.view.RemotableViewMethod
public synchronized void setIndeterminate(boolean indeterminate) 

Source Link

Document

Change the indeterminate mode for this progress bar.

Usage

From source file:com.somethoughts.chinmay.game.Coin.CoinTossMainFragment.java

private void toss_it(final Boolean userChoice) {

    if (inProgress) {
        Toast.makeText(getActivity(), "Please Wait", Toast.LENGTH_SHORT).show();
        return;//from   w  ww  .j  a v a2s.  c  o  m
    }
    final TextView textViewResult = (TextView) view.findViewById(R.id.coin_result_textview);
    final TextView textViewStatus = (TextView) view.findViewById(R.id.coin_status_textView);
    final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.coin_progressBar);

    Random random = new Random();
    progressBar.setVisibility(View.VISIBLE);
    progressBar.setMax(2500);
    progressBar.setIndeterminate(false);
    final Boolean b = random.nextBoolean();
    countDownTimer = new CountDownTimer(3000, 125) {
        @Override
        public void onTick(long l) {
            inProgress = true;
            Random random = new Random();
            progressBar.setProgress(3000 - (int) l);
            Log.v("Progress", Integer.toString(progressBar.getProgress()));
            textViewStatus.setVisibility(View.VISIBLE);
            textViewStatus.setText(toss[random.nextInt(2)]);
            textViewResult.setText(getResources().getText(R.string.Waiting));
        }

        @Override
        public void onFinish() {
            inProgress = false;
            if ((b && userChoice) || (!b && !userChoice)) {

                textViewStatus.setText(getResources().getText(R.string.Voila));
                view.setBackgroundColor(getColor(getActivity().getBaseContext(), R.color.colorWin));
                if (userChoice)
                    textViewResult.setText(toss[0]);
                else
                    textViewResult.setText(toss[1]);
            } else {
                textViewStatus.setText(getResources().getText(R.string.oops));
                view.setBackgroundColor(getColor(getActivity().getBaseContext(), R.color.colorLose));
                if (userChoice)
                    textViewResult.setText(toss[1]);
                else
                    textViewResult.setText(toss[0]);
            }
            progressBar.setProgress(3000);
        }
    }.start();
}

From source file:org.quantumbadger.redreader.activities.AlbumListingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    PrefsUtility.applyTheme(this);

    OptionsMenuUtility.fixActionBar(AlbumListingActivity.this, getString(R.string.imgur_album));

    if (getActionBar() != null) {
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }//from w  ww  .  j  a va  2  s.  co  m

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final boolean solidblack = PrefsUtility.appearance_solidblack(this, sharedPreferences)
            && PrefsUtility.appearance_theme(this, sharedPreferences) == PrefsUtility.AppearanceTheme.NIGHT;

    if (solidblack)
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));

    final Intent intent = getIntent();

    mUrl = intent.getDataString();

    if (mUrl == null) {
        finish();
        return;
    }

    final Matcher matchImgur = LinkHandler.imgurAlbumPattern.matcher(mUrl);
    final String albumId;

    if (matchImgur.find()) {
        albumId = matchImgur.group(2);
    } else {
        Log.e("AlbumListingActivity", "URL match failed");
        revertToWeb();
        return;
    }

    Log.i("AlbumListingActivity", "Loading URL " + mUrl + ", album id " + albumId);

    final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
    progressBar.setIndeterminate(true);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(progressBar);

    ImgurAPI.getAlbumInfo(this, albumId, Constants.Priority.IMAGE_VIEW, 0, new GetAlbumInfoListener() {

        @Override
        public void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {
            Log.e("AlbumListingActivity", "getAlbumInfo call failed: " + type);

            if (status != null)
                Log.e("AlbumListingActivity", "status was: " + status.toString());
            if (t != null)
                Log.e("AlbumListingActivity", "exception was: ", t);

            // It might be a single image, not an album

            if (status == null) {
                revertToWeb();
                return;
            }

            ImgurAPI.getImageInfo(AlbumListingActivity.this, albumId, Constants.Priority.IMAGE_VIEW, 0,
                    new GetImageInfoListener() {
                        @Override
                        public void onFailure(final RequestFailureType type, final Throwable t,
                                final StatusLine status, final String readableMessage) {
                            Log.e("AlbumListingActivity", "Image info request also failed: " + type);
                            revertToWeb();
                        }

                        @Override
                        public void onSuccess(final ImageInfo info) {
                            Log.i("AlbumListingActivity", "Link was actually an image.");
                            LinkHandler.onLinkClicked(AlbumListingActivity.this, info.urlOriginal);
                            finish();
                        }

                        @Override
                        public void onNotAnImage() {
                            Log.i("AlbumListingActivity", "Not an image either");
                            revertToWeb();
                        }
                    });
        }

        @Override
        public void onSuccess(final ImgurAPI.AlbumInfo info) {
            Log.i("AlbumListingActivity", "Got album, " + info.images.size() + " image(s)");

            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {

                    if (info.title != null && !info.title.trim().isEmpty()) {
                        OptionsMenuUtility.fixActionBar(AlbumListingActivity.this,
                                getString(R.string.imgur_album) + ": " + info.title);
                    }

                    layout.removeAllViews();

                    final ListView listView = new ListView(AlbumListingActivity.this);
                    listView.setAdapter(new AlbumAdapter(info));
                    layout.addView(listView);

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(final AdapterView<?> parent, final View view,
                                final int position, final long id) {

                            LinkHandler.onLinkClicked(AlbumListingActivity.this,
                                    info.images.get(position).urlOriginal, false, null, info, position);
                        }
                    });
                }
            });
        }
    });

    setContentView(layout);
}

From source file:com.hijacker.InstallFirmwareDialog.java

@Override
public void onStart() {
    super.onStart();
    //Override positiveButton action to dismiss the fragment only when the directories exist, not on error
    AlertDialog d = (AlertDialog) getDialog();
    if (d != null) {
        final Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
        Button neutralButton = d.getButton(Dialog.BUTTON_NEUTRAL);
        positiveButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override/*from  w w  w.ja v  a2s.  c o m*/
            public boolean onLongClick(View v) {
                v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                attemptInstall(true);
                return false;
            }
        });
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptInstall(false);
            }
        });
        neutralButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                positiveButton.setActivated(false);
                ProgressBar progress = (ProgressBar) dialogView.findViewById(R.id.install_firm_progress);
                progress.setIndeterminate(true);
                shell.run(busybox + " find /system/ -type f -name \"fw_bcmdhd.bin\"; echo ENDOFFIND");

                String lastline = getLastLine(shell.getShell_out(), "ENDOFFIND");
                if (lastline.equals("ENDOFFIND")) {
                    Snackbar.make(v, R.string.firm_notfound_bcm, Snackbar.LENGTH_LONG).show();
                } else {
                    lastline = lastline.substring(0, lastline.length() - 14);
                    firmView.setText(lastline);
                }

                progress.setIndeterminate(false);
                positiveButton.setActivated(true);
            }
        });
    }
}

From source file:io.github.minime89.passbeam.activities.KeyboardLayoutActivity.java

private void setupKeyboardLayoutMenu() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        ProgressBar progressBar = new ProgressBar(this);
        progressBar.setVisibility(View.GONE);
        progressBar.setIndeterminate(true);

        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL);
        progressBar.setLayoutParams(layoutParams);

        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(progressBar);
    }/*  www .j  a  v  a 2 s.c  om*/
}

From source file:com.metaphyze.hackernewsfrontpage.HackerNewsFrontPageActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hacker_news_front_page);

    bookFileName = getFilesDir() + File.separator + "bookmarked_posts.js";
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.drawer);
    location = (TextView) findViewById(R.id.location);

    webView = (WebView) findViewById(R.id.content_frame);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    loadingView = findViewById(R.id.loading);
    ProgressBar progressBar = ((ProgressBar) findViewById(R.id.progress_bar));
    progressBar.setIndeterminate(true);
    drawerList.setAdapter(new HackerNewsAdapter(HackerNewsFrontPageActivity.this, R.layout.post_item,
            new ArrayList<HackerNewsPost>(), true));
    getActionBar().setTitle("Hacker News Front Page (Loading Live Stream...)");
    drawerList.setOnItemClickListener(new OnItemClickListener() {

        @Override/* ww  w.j ava  2  s  . c  om*/
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HackerNewsPost post = (HackerNewsPost) parent.getItemAtPosition(position);

            webView.loadUrl(post.getUrl());
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    loadingView.setVisibility(View.VISIBLE);
                    location.setText("LOADING......" + url);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    loadingView.setVisibility(View.INVISIBLE);
                    location.setText(url);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description,
                        String failingUrl) {
                    loadingView.setVisibility(View.INVISIBLE);
                    location.setText("ERROR LOADING PAGE");
                    view.loadUrl("file:///android_asset/failed_to_load_page.html");
                }

            });
            drawerLayout.closeDrawer(drawerList);
        }
    });

    drawerList.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            final HackerNewsPost clonedPost = ((HackerNewsPost) parent.getItemAtPosition(position)).clone();
            clonedPost.setPostedAgo(new Date().toString());
            AlertDialog.Builder builder = new AlertDialog.Builder(HackerNewsFrontPageActivity.this);
            if (((HackerNewsAdapter) parent.getAdapter()).isLive()) {
                builder.setTitle("Bookmark?");
                builder.setMessage("Do you want to bookmark the post\n" + clonedPost.getTitle());
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            HackerNewsFrontPageContents contents = readContentsFromBookmarksFile();
                            if (contents == null) {
                                showError("ERROR", "Failed to read bookmark file");
                                dialog.dismiss();
                                return;
                            }

                            if (!contents.addPost(clonedPost)) {
                                showError("Already Exists", "Not added becasue bookmark already exists");
                                dialog.dismiss();
                                return;
                            }

                            if (!saveContentsToBookmarksFile(contents)) {
                                showError("ERROR", "Failed to save bookmark");
                                dialog.dismiss();
                            }

                        } catch (Exception ex) {
                            ex.printStackTrace();
                            showError("ERROR", "Internal error: " + ex);
                        }
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            } else {
                builder.setTitle("Delete?");
                builder.setMessage("Do you want to delete the bookmarked post:\n" + clonedPost.getTitle());
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {

                            HackerNewsFrontPageContents contents = readContentsFromBookmarksFile();
                            if (contents == null) {
                                showError("ERROR", "Unable to find or generate bookmarks file");
                                dialog.dismiss();
                                return;
                            }

                            if (!contents.removePost(clonedPost)) {
                                showError("Not Removed", "Does not exist? How's that possible?");
                                dialog.dismiss();
                                return;
                            }

                            if (saveContentsToBookmarksFile(contents)) {
                                if (contents.getItems().size() > 0) {
                                    drawerList
                                            .setAdapter(new HackerNewsAdapter(HackerNewsFrontPageActivity.this,
                                                    R.layout.post_item, contents.getItems(), false));
                                } else {
                                    showError("No more bookmarks", "Reverting to live stream");
                                    loadLiveStream();
                                }
                            } else {
                                showError("ERROR", "Failed to save bookmark deletion");
                            }
                            dialog.dismiss();

                        } catch (Exception ex) {
                            ex.printStackTrace();
                            showError("ERROR", "Internal Error: " + ex);
                        }

                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }

            builder.setCancelable(true);
            builder.create().show();

            return false;
        }
    });

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.drawer_icon, 0, 0);
    drawerLayout.setDrawerListener(drawerToggle);

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    //      actionBar.setHomeButtonEnabled(true);

    requestQueue = Volley.newRequestQueue(this);
    loadLiveStream();

}

From source file:de.zell.android.util.fragments.WebviewFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_webview, container, false);
    if (url != null && !url.isEmpty()) {
        content = ((WebView) rootView.findViewById(R.id.webview));
        //WebViewClient is enabled in order to force all links to load within the webview and also
        // in order to enable JavaScript
        content.setWebViewClient(new HelloWebViewClient());
        WebSettings webSettings = content.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);

        final ProgressBar progressBar = ((MainNavigationActivity) getActivity()).getProgressBar();
        content.setWebChromeClient(new WebChromeClient() {
            @Override/*w w  w. jav a  2s .  c  o  m*/
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                if (newProgress == 100)
                    progressBar.setVisibility(View.GONE);
            }
        });

        progressBar.setIndeterminate(true);
        progressBar.setVisibility(View.VISIBLE);
        content.loadUrl(url);
    }

    getActivity().setTitle(title);
    return rootView;
}

From source file:app.sunstreak.yourpisd.ClassSwipeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //      requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_class_swipe);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);/* w  ww  . j a  v  a 2  s  .  c om*/
    }
    ProgressBar spinner = new ProgressBar(this);
    spinner.setIndeterminate(true);
    spinner.setId(R.id.action_bar_spinner);
    spinner.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
    toolbar.addView(spinner);
    receivedClassIndex = getIntent().getExtras().getInt("classIndex");
    classCount = getIntent().getExtras().getInt("classCount");
    termIndex = getIntent().getExtras().getInt("termIndex");
    studentIndex = getIntent().getExtras().getInt("studentIndex");

    setTitle(TermFinder.Term.values()[termIndex].name);

    session = ((YPApplication) getApplication()).session;

    session.studentIndex = studentIndex;
    student = session.getCurrentStudent();
    classesForTerm = student.getClassesForTerm(termIndex);

    System.out.println(classesForTerm);

    mFragments = new ArrayList<Fragment>();
    for (int i = 0; i < classesForTerm.size(); i++) {
        Bundle args = new Bundle();
        args.putInt(DescriptionFragment.ARG_SECTION_NUMBER, i);
        Fragment fragment = new DescriptionFragment();
        fragment.setArguments(args);
        mFragments.add(fragment);
    }

    // Create the adapter that will return a fragment for each of the 
    // primary sections of the app.

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), mFragments);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    //      final ActionBar actionBar = getActionBar();
    //      actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    /*
    for(int i = 0; i< classCount; i++)
    {
       actionBar.addTab(actionBar.newTab()
       .setText(session.getCurrentStudent()
             .getClassName(session.getCurrentStudent().getClassMatch()[i]))
             .setTabListener(this));
    }
     */

    //      for (int classIndex : classesForTerm)
    //         actionBar.addTab(actionBar.newTab().setText(student.getClassName(student.getClassMatch()[classIndex]))
    //               .setTabListener(this));
    ArrayList<String> temp = new ArrayList<>();
    for (int classIndex : classesForTerm) {
        temp.add(student.getClassName(student.getClassMatch()[classIndex]));
    }

    setUpMaterialTabs(temp);
    //      mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    //
    //         @Override
    //         public void onPageSelected(int position) {
    //            // on changing the page
    //            // make respected tab selected
    //            actionBar.setSelectedNavigationItem(position);
    //         }
    //
    //         @Override
    //         public void onPageScrolled(int arg0, float arg1, int arg2) {
    //         }
    //
    //         @Override
    //         public void onPageScrollStateChanged(int arg0) {
    //         }
    //      });
    //
    System.out.println("received class index = " + receivedClassIndex);
    if (receivedClassIndex > 0 && receivedClassIndex < classesForTerm.size())
        mViewPager.setCurrentItem(receivedClassIndex);
    // otherwise, current item is defaulted to 0

    //      mViewPager.setOffscreenPageLimit(5);

}

From source file:com.money.manager.ex.home.DashboardFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // add progress bar
    ProgressBar progressBar = new ProgressBar(getActivity());
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);//from www .  j  ava 2  s  .c  om
    layoutParams.gravity = Gravity.CENTER;
    progressBar.setLayoutParams(layoutParams);
    progressBar.setIndeterminate(true);

    if (id <= ID_LOADER_SCREEN4) {
        linearScreens[id].removeAllViews();
        // add view
        linearScreens[id].addView(progressBar);
    }

    Select query;

    // start loader
    switch (id) {
    case ID_LOADER_SCREEN1:
        QueryReportIncomeVsExpenses report = new QueryReportIncomeVsExpenses(getActivity());
        query = new Select(report.getAllColumns()).where(IncomeVsExpenseReportEntity.Month + "="
                + Integer.toString(Calendar.getInstance().get(Calendar.MONTH) + 1) + " AND "
                + IncomeVsExpenseReportEntity.YEAR + "="
                + Integer.toString(Calendar.getInstance().get(Calendar.YEAR)));

        return new MmxCursorLoader(getActivity(), report.getUri(), query);

    case ID_LOADER_SCREEN2:
        query = new Select().where(prepareQueryTopWithdrawals());
        return new MmxCursorLoader(getActivity(), new SQLDataSet().getUri(), query);

    case ID_LOADER_SCREEN3:
        query = new Select().where(prepareQueryTopPayees());
        return new MmxCursorLoader(getActivity(), new SQLDataSet().getUri(), query);

    case ID_LOADER_SCREEN4:
        QueryBillDeposits billDeposits = new QueryBillDeposits(getActivity());
        query = new Select(billDeposits.getAllColumns()).where(QueryBillDeposits.DAYSLEFT + "<=10")
                .orderBy(QueryBillDeposits.DAYSLEFT);

        return new MmxCursorLoader(getActivity(), billDeposits.getUri(), query);
    }
    return null;
}

From source file:net.bluehack.ui.WallpapersActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("ChatBackground", R.string.ChatBackground));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//from w  ww  . j  a  v a2  s .  c o m
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                boolean done;
                TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
                if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) {
                    int width = AndroidUtilities.displaySize.x;
                    int height = AndroidUtilities.displaySize.y;
                    if (width > height) {
                        int temp = width;
                        width = height;
                        height = temp;
                    }
                    TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes,
                            Math.min(width, height));
                    String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
                    File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE),
                            fileName);
                    File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg");
                    try {
                        done = AndroidUtilities.copyFile(f, toFile);
                    } catch (Exception e) {
                        done = false;
                        FileLog.e("tmessages", e);
                    }
                } else {
                    if (selectedBackground == -1) {
                        File fromFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper-temp.jpg");
                        File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg");
                        done = fromFile.renameTo(toFile);
                    } else {
                        done = true;
                    }
                }

                if (done) {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt("selectedBackground", selectedBackground);
                    editor.putInt("selectedColor", selectedColor);
                    editor.commit();
                    ApplicationLoader.reloadWallpaper();
                }
                finishFragment();
            }
        }
    });

    ActionBarMenu menu = actionBar.createMenu();
    doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));

    FrameLayout frameLayout = new FrameLayout(context);
    fragmentView = frameLayout;

    backgroundImage = new ImageView(context);
    backgroundImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
    frameLayout.addView(backgroundImage,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    backgroundImage.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    frameLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 52));

    progressViewBackground = new View(context);
    progressViewBackground.setBackgroundResource(R.drawable.system_loader);
    progressView.addView(progressViewBackground, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    RecyclerListView listView = new RecyclerListView(context);
    listView.setClipToPadding(false);
    listView.setTag(8);
    listView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    listView.setLayoutManager(layoutManager);
    listView.setDisallowInterceptTouchEvents(true);
    listView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    listView.setAdapter(listAdapter = new ListAdapter(context));
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 102, Gravity.LEFT | Gravity.BOTTOM));
    listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (position == 0) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());

                CharSequence[] items = new CharSequence[] {
                        LocaleController.getString("FromCamera", R.string.FromCamera),
                        LocaleController.getString("FromGalley", R.string.FromGalley),
                        LocaleController.getString("Cancel", R.string.Cancel) };

                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            if (i == 0) {
                                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File image = AndroidUtilities.generatePicturePath();
                                if (image != null) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", image));
                                        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    } else {
                                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                Uri.fromFile(image));
                                    }
                                    currentPicturePath = image.getAbsolutePath();
                                }
                                startActivityForResult(takePictureIntent, 10);
                            } else if (i == 1) {
                                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                                photoPickerIntent.setType("image/*");
                                startActivityForResult(photoPickerIntent, 11);
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    }
                });
                showDialog(builder.create());
            } else {
                if (position - 1 < 0 || position - 1 >= wallPapers.size()) {
                    return;
                }
                TLRPC.WallPaper wallPaper = wallPapers.get(position - 1);
                selectedBackground = wallPaper.id;
                listAdapter.notifyDataSetChanged();
                processSelectedBackground();
            }
        }
    });

    processSelectedBackground();

    return fragmentView;
}

From source file:kr.wdream.ui.WallpapersActivity.java

@Override
public View createView(Context context) {
    Log.d(LOG_TAG, "createView");

    actionBar.setBackButtonImage(kr.wdream.storyshop.R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(//www .  ja  v a2  s  .c o  m
            LocaleController.getString("ChatBackground", kr.wdream.storyshop.R.string.ChatBackground));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                boolean done;
                TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
                if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) {
                    int width = AndroidUtilities.displaySize.x;
                    int height = AndroidUtilities.displaySize.y;
                    if (width > height) {
                        int temp = width;
                        width = height;
                        height = temp;
                    }
                    TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes,
                            Math.min(width, height));
                    String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
                    File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE),
                            fileName);
                    File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg");
                    try {
                        done = AndroidUtilities.copyFile(f, toFile);
                    } catch (Exception e) {
                        done = false;
                        FileLog.e("tmessages", e);
                    }
                } else {
                    if (selectedBackground == -1) {
                        File fromFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper-temp.jpg");
                        File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg");
                        done = fromFile.renameTo(toFile);
                    } else {
                        done = true;
                    }
                }

                if (done) {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt("selectedBackground", selectedBackground);
                    editor.putInt("selectedColor", selectedColor);
                    editor.commit();
                    ApplicationLoader.reloadWallpaper();
                }
                finishFragment();
            }
        }
    });

    ActionBarMenu menu = actionBar.createMenu();
    doneButton = menu.addItemWithWidth(done_button, kr.wdream.storyshop.R.drawable.ic_done,
            AndroidUtilities.dp(56));

    FrameLayout frameLayout = new FrameLayout(context);
    fragmentView = frameLayout;

    backgroundImage = new ImageView(context);
    backgroundImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
    frameLayout.addView(backgroundImage,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    backgroundImage.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    frameLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 52));

    progressViewBackground = new View(context);
    progressViewBackground.setBackgroundResource(kr.wdream.storyshop.R.drawable.system_loader);
    progressView.addView(progressViewBackground, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(
                context.getResources().getDrawable(kr.wdream.storyshop.R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    RecyclerListView listView = new RecyclerListView(context);
    listView.setClipToPadding(false);
    listView.setTag(8);
    listView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    listView.setLayoutManager(layoutManager);
    listView.setDisallowInterceptTouchEvents(true);
    listView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    listView.setAdapter(listAdapter = new ListAdapter(context));
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 102, Gravity.LEFT | Gravity.BOTTOM));
    listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (position == 0) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());

                CharSequence[] items = new CharSequence[] {
                        LocaleController.getString("FromCamera", kr.wdream.storyshop.R.string.FromCamera),
                        LocaleController.getString("FromGalley", kr.wdream.storyshop.R.string.FromGalley),
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel) };

                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            if (i == 0) {
                                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File image = AndroidUtilities.generatePicturePath();
                                if (image != null) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", image));
                                        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    } else {
                                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                Uri.fromFile(image));
                                    }
                                    currentPicturePath = image.getAbsolutePath();
                                }
                                startActivityForResult(takePictureIntent, 10);
                            } else if (i == 1) {
                                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                                photoPickerIntent.setType("image/*");
                                startActivityForResult(photoPickerIntent, 11);
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    }
                });
                showDialog(builder.create());
            } else {
                if (position - 1 < 0 || position - 1 >= wallPapers.size()) {
                    return;
                }
                TLRPC.WallPaper wallPaper = wallPapers.get(position - 1);
                selectedBackground = wallPaper.id;
                listAdapter.notifyDataSetChanged();
                processSelectedBackground();
            }
        }
    });

    processSelectedBackground();

    return fragmentView;
}