#ProgressDialog
Explore tagged Tumblr posts
technxt-code-labs-blog · 6 years ago
Link
1 note · View note
draegerit · 4 years ago
Text
Android Programmierung: AsyncTask mit ProgressDialog (Lösung mit einem Callback)
Tumblr media
In diesem Tutorial möchte ich beschreiben wie man eine asynchrone Aufgabe auslagert und parallel dazu einen Dialog anzeigt. Den ProgressDialog habe ich bereits im Tutorial Android, ProgressDialog für lange Operationen erläutert. Es gibt bereits einige Beispiele dazu im Internet und die Lösungen sind zumeist praktikabel und funktionell. Jedoch sind diese zumeist mit einer inneren Klasse (wie in der offiziellen Dokumentation https://developer.android.com/reference/android/os/AsyncTask) und blähen dadurch den Quellcode unnötig auf. Ich möchte gerne einen anderen Weg gehen und den AsyncTask auslagern und mit einem Callback versehen so halten wir unseren Quellcode schlank und haben immer das Wesentliche im blick.
Projekt erstellen
Für die nachfolgenden Schritte benötigen wir ein einfaches, leeres Android Projekt mit einer Activity (EmptyActivity).  Gerne möchte ich dir der einfachheithalber ein Download für ein Projekt anbieten welches du dir in Android Studio importieren kannst.   Layout erstellen Für das Ausführen des asynchronen Task benötigen wir eine Schaltfläche und für die Anzeige der Daten  TextView Elemente. Diese Elemente fügen wir über den Designer auf das Layout "activity_main.xml".
Interface ICallback erzeugen
Für die Verarbeitung des Ergebnisses unseres asynchronen Tasks benötigen wir ein Interfaces. Dieses ermöglicht es uns späterer mehrere Implementationen für eventuelle verschiedene Ausführungen zu implementieren. package de.draegerit.asynctaskcallbackapp; public interface ICallback { void handleResult(Result result); } Nun müssen wir uns eine innere Klasse schreiben welche das Interface "ICallback" implementiert. Mit dem implementieren des Interfaces müssen wir zusätzlich die Methode "handleResult" implementieren. class CallbackImpl implements ICallback { @Override public void handleResult(Result result) { } } package de.draegerit.asynctaskcallbackapp; public class Result { private int size; private String filename; private String message; public int getSize() { return size; } public void setSize(int size) { this.size = size; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } }
asynchronen Task erstellen
Nun können wir uns eine öffentliche Klasse für den asynchronen Task erstellen welchen wir mit der Schaltfläche starten wollen. In diesem Beispiel möchte ich eine einfache Datei aus dem Internet laden. Da ich in diesem Tutorial beschreiben möchte wie ein asynchroner Task mit einem Callback ausgestattet werden kann überspringe ich die Erläuterungen für das herunterladen von Dateien. In dem Kontruktors des asynchronen Task wird der Context und zusätzlich ein Callback übergeben. package de.draegerit.asynctaskcallbackapp; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.util.Log; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.URL; import java.net.URLConnection; public class RequestAsyncTask extends AsyncTask { //TAG für den Logger private static final String TAG = "RequestAsyncTask"; //Zieldatei private static final String ADDRESS = "http://progs.draeger-it.blog/example.file"; //Schwache Referenz auf den Context private WeakReference contextRef; //ProgressDialog für die Fortschrittsanzeige private ProgressDialog progressDialog; //Das Ergebniss des asynchronen Tasks private Result result; //Der Callback welcher zum schluss ausgeführt werden soll. private ICallback callback; //Variable welche gesetzt wird wenn die Schaltfläche "Abbrechen" im ProgressDialog betätigt wird. private boolean abortDownload; /** * Konstruktor * @param ctx - der Context * @param callback - der Callback welcher zum Schluss ausgeführt werden soll */ public RequestAsyncTask(Context ctx, ICallback callback) { contextRef = new WeakReference(ctx); this.callback = callback; } @Override protected Result doInBackground(Void... voids) { result = new Result(); try { //Die Progressbar soll den Fortschritt in Prozent anzeigen. progressDialog.setMax(100); DataInputStream stream = null; //Dateiname generieren String filename = String.valueOf(System.currentTimeMillis()).concat(".file"); result.setFilename(filename); //Referenz des Context laden Context ctx = contextRef.get(); try (FileOutputStream outputStream = ctx.openFileOutput(filename, Context.MODE_PRIVATE);){ File privateFileDirectory = ctx.getFilesDir(); Log.i(TAG, privateFileDirectory.getAbsolutePath()); //Aufbau der Verbindung URL u = new URL(ADDRESS); URLConnection conn = u.openConnection(); //ermitteln der Dateigröße int contentLength = conn.getContentLength(); //ablegen der Dateigröße in unseren Result result.setSize(contentLength); //Datenstream ��ffnen stream = new DataInputStream(u.openStream()); byte buffer = new byte; int count; int total = 0; int percent; //Solange der Stream noch Daten hat und die Variable abortDownload nicht Boolean.True ist, mache... while (((count = stream.read(buffer)) != -1) && !abortDownload) { outputStream.write(buffer, 0, count); total += count; percent = (total * 100) / contentLength; progressDialog.setProgress(percent); } } catch (Exception e) { //Wenn ein Fehler auftritt so soll dieser in unser Result gespeichert werden. result.setMessage(e.getMessage()); e.printStackTrace(); } finally { //Zum Schluss den Datenstream schließen if (stream != null) { try { stream.close(); } catch (IOException e) { //Wenn ein Fehler auftritt so soll dieser in unser Result gespeichert werden. result.setMessage(e.getMessage()); e.printStackTrace(); } } } } catch (Exception e) { //Wenn ein Fehler auftritt so soll dieser in unser Result gespeichert werden. result.setMessage(e.getMessage()); e.printStackTrace(); } //Rückgabe unseres Ergebnisses. return result; } @Override protected void onPreExecute() { super.onPreExecute(); //Anzeigen des ProgressDialoges, //dieses geschieht noch bevor der Download gestartet wird. progressDialog = getWaitDialog(); progressDialog.show(); } @Override protected void onPostExecute(Result result) { super.onPostExecute(result); //nach dem Download (erfolgreich oder nicht) //soll der ProgressDialog geschlossen werden. progressDialog.dismiss(); //Ausführen des Callbacks callback.handleResult(result); } /** * Liefert einen ProgressDialog * @return ein ProgressDialog */ private ProgressDialog getWaitDialog() { Context context = contextRef.get(); String titel = context.getResources().getString(R.string.msg_loaddialog_titel); String message = context.getResources().getString(R.string.msg_loaddialog_message); ProgressDialog progressDialog = new ProgressDialog(context); progressDialog.setTitle(titel); progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setButton(ProgressDialog.BUTTON_POSITIVE, context.getResources().getString(R.string.abort), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { abortDownload = true; } }); return progressDialog; } } Für dieses Beispiel habe ich eine Datei mit ca. 30MB auf eine Subdomain (http://progs.draeger-it.blog/example.file) geladen. Ich kann & möchte nicht garantieren das diese Datei auf ewig bereitgestellt wird. Die Datei selbst habe ich mit dem Befehl "fsutil file createnew example.file 3000000" unter Microsoft Windows 10 erstellt.
Tumblr media
ProgressDialog - Download im Vorgang Wichtig ist hier die Methode "onPostExecute", diese Methode wird zum Schluss ausgeführt und in diesem Beispiel werde ich hier den Callback aufrufen. @Override protected void onPostExecute(Result result) { super.onPostExecute(result); //nach dem Download (erfolgreich oder nicht) //soll der ProgressDialog geschlossen werden. progressDialog.dismiss(); //Ausführen des Callbacks callback.handleResult(result); }
Ausführen des asynchronen Task
Für das Ausführen des asynchronen Task haben wir im ersten Schritt eine Schaltfläche erzeugt. Nun wollen wir an diese Schaltfläche einen Listener hängen und in diesem den Task starten. public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startBtn = findViewById(R.id.startBtn); startBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RequestAsyncTask requestAsyncTask = new RequestAsyncTask(MainActivity.this, new CallbackImpl()); requestAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); } Nun müssen wir noch ein Callback implementieren. In diesem Callback werde ich 2 Textfelder (jeweils mit Dateiname, Dateigröße) und / oder ein Feld mit der Fehlermeldung einer Exception befüllen. class CallbackImpl implements ICallback { @Override public void handleResult(Result result) { //Wenn das Feld "message" leer bzw. NULL ist dann ist kein Fehler aufgetreten. boolean showErrorMessage = result.getMessage() == null; TextView errorMsgTextView = findViewById(R.id.errorMsgTextView); //Wenn keine Fehlermeldung aufgetreten ist dann soll das TextView Element ausgeblendet werden. errorMsgTextView.setVisibility(showErrorMessage ? View.VISIBLE : View.INVISIBLE); if(showErrorMessage){ errorMsgTextView.setText(result.getMessage()); } TextView dateinameTextView = findViewById(R.id.dateinameTextView); dateinameTextView.setText(result.getFilename()); TextView dateigroesseTextView = findViewById(R.id.dateigroesseTextView); dateigroesseTextView.setText(String.valueOf(result.getSize()).concat(" byte")); } }
Download
Fazit
Das auslagern des asynchronen Task hat mir geholfen ein bereits bestehendes Projekt deutlich zu verschlanken. Man könnte nun statt einem Callback auch ein funktionales Interface nutzen jedoch geht dieses erst ab Java 8.      Read the full article
0 notes
eiheducation · 3 years ago
Text
How to use ProgressBar in Android Studio?
Developers are always interested in knowing how to utilize ProgressBar to their advantage in Android Studio. It's a regular part of their life and they have to utilize ProgressBar for their jobs. It's element of their life as well as their work. They have to learn how to utilize ProgressBar inside Android Studio. They will not be able to live without ProgressBar.
The Best Java Books for Beginners in 2022
1. Introduction
ProgressBar is used to display the progress of an procedure or task. This is often useful when the status of the operation is not apparent until the task has been completed. ProgressBar is generally used in conjunction with the ProgressDialog. The ProgressBar can also be useful for animating the progress of a process.
CCNA Routing And Switching All In One Study Guide BOOK
2. How to add ProgressBar
You can use ProgressBar in Android Studio. It will track the progression of your app. You can add a ProgressBar to your activity by following these steps: 1. Add the ProgressBar widget in your layout file. Set the height and width of the widget to your desired values 3. The background color should be set to 4. Add the following line to the XML file < ProgressBar 5. Incorporate the next line into the XML file < ProgressBar 6. Incorporate the next line into the XML file < ProgressBar 7. Incorporate the next line into the XML file < ProgressBar 8. Add the following line to the XML file ProgressBar 9. Incorporate the next line into the XML file < ProgressBar 10. Incorporate the next line into the XML file ProgressBar 11. Add the following line to the XML file: ProgressBar 12. The following lines should be added to the XML file ProgressBar 13. The following lines should be added to the XML file: ProgressBar 14. Include the line below to the XML file
How To Configure EIGRP On Cisco Router Step By Step Guide - 4 Routers
3. How to use ProgressBar
ProgressBar is an extremely useful tool available in Android Studio. It's an excellent tool to help you in the development process. ProgressBar is an application that shows the amount of progress you've made within your project. It is found on the left-hand side of the Android Studio window. It is also possible to include the ProgressBar to your layout file, and it will automatically appear within the windows. You can change the color of the ProgressBar via its Properties menu. You can also change your color for the ProgressBar via the Properties menu.
How To Configure OSPF Single Area On 4 Routers In Cisco Packet Tracer
4. Conclusion.
A method of monitoring the current process of a project is to use the progress bar. These bars show the status of a task the user. The progress bar provides an image representation of the task that has been initiated and is in progress. This can be done by using a progress indicator in Android Studio.
How To Configure EIGRP in Packet Tracer - 3 Routers
0 notes
developerhelp · 3 years ago
Text
How to show a loading gif while an APi is being called in xamarin android?
How to show a loading gif while an APi is being called in xamarin android?
You can do it like this: private void BtnConsumer_Click(object sender, EventArgs e) { CustomProgressDialog progressDialog = CustomProgressDialog.Show(this); try { String cpfConsumer = edtCpf.Text; Pessoa pessoa = this.GetConsumer(cpfConsumer); List<String> lista = this.GetServiceOrders(cpfConsumer); txtnome.Text = "Nome: " + pessoa.firstName + " " + pessoa.lastName; ArrayAdapter<string> adapter…
View On WordPress
0 notes
javatutorial4y · 7 years ago
Photo
Tumblr media
@javacodegeeks : #Android ProgressDialog Example https://t.co/VWV4g1CXRe
1 note · View note
android-arsenal · 6 years ago
Text
KLoadingSpin
KLoadingSpin is an alternative to progressDialog used widely in android.
Tumblr media
from The Android Arsenal https://ift.tt/2zFH4Pf
0 notes
youngcutelusty · 6 years ago
Text
Create A Download Monitor with Android and Kotlin
Tumblr media
Kotlin is becoming increasingly popular these days and is widely used in the development of Android. This article will show how Kotlin can be used in the
Android app development
. Set the Environment Download Android Studio 3.0 from the Google site if you have not already installed it. This article uses Android Studio 3.0. The reason I use Android Studio is that it already supports Kotlin, so you do not need to download it. For earlier versions of Android Studio, you must manually add support from Kotlin. Create an Android project with an empty activity. At the moment, an Android project has been created, but Kotlin's development is not supported. We will add it later. Gradle Script Download the tracker Create a Kotlin class by right clicking on the project and calling it DownloadActivity. A file with the extension ".kt" will be created. Download activity As suspicious, this is an AsyncTask that downloads the file from the Internet. At the moment we hard coded the URL. The URL is a PDF file. You can change this value as you prefer. We will define the class below with an internal Kotlin class. And we need to override methods like onPreExecute, doInBackground, onPostExecute, onProgressUpdate, and so on. Next, a progress dialog must be displayed when the download starts. During the definition of an asynchronous activity, we passed an instance of ProgressDialog to the constructor. This type of constructor is called the main constructor because it does not contain any code. Note that we did not assign the ProgressDialog instance to any variables. However, you can access it from any class method. This is because Kotlin treats it implicitly as a property and uses it to initialize properties. Next, the file download code is encoded using a standard URLConnection API. The above code opens a URL link to the site and creates a buffered input stream object with the default value of BUFFER_SIZE. BUFFER_SIZE is here a final static variable with a value of 8192. We will see how we can define a definitive static variable in Kotlin. The second line in the code snippet above reads data from the stream until it becomes zero. So, the cycle is left. The true beauty of Kotlin. The rest of the code calculates the percentage earned during the download and the update of the progress dialog.
0 notes
fbreschi · 6 years ago
Text
Replace ProgressDialog with a progress button in your app
http://dlvr.it/R3gxhb
0 notes
technxt-code-labs-blog · 6 years ago
Text
How to create Progress Dialog in android ?
A dialog showing a progress indicator and an optional text message or view. Only a text message or a view can be used at the same time. Progress Dialog is an extends class of Alert Dialog or It is an extension of Alert Dialog . Progress Dialog is used to show the progress of a task that takes some time to complete .
0 notes
re-take21 · 6 years ago
Text
【Android】DeprecatedのProgressDialogを倒してProgressBarを実装した話【kotlin】
【Android】DeprecatedのProgressDialogを倒してProgressBarを実装した話【kotlin】 #android #kotlin #TwitMorse
Androidアプリを書いている人は既に既知の問題だとは思いますが、API26にてProgressDialogがDeprecatedになりました。
ProgressDialog | Android Developer
This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app’s UI. Alternatively, you can use a…
View On WordPress
0 notes
javatutorial4u · 6 years ago
Photo
Tumblr media
#Android ProgressDialog Example https://t.co/VWV4g1CXRe #Java #JavaEE #Java9
0 notes
eiheducation · 3 years ago
Text
How to use ProgressBar in Android Studio?
Developers are always interested in knowing how to utilize ProgressBar to their advantage in Android Studio. It's a regular part of their life and they have to utilize ProgressBar for their jobs. It's element of their life as well as their work. They have to learn how to utilize ProgressBar inside Android Studio. They will not be able to live without ProgressBar.
The Best Java Books for Beginners in 2022
1. Introduction
ProgressBar is used to display the progress of an procedure or task. This is often useful when the status of the operation is not apparent until the task has been completed. ProgressBar is generally used in conjunction with the ProgressDialog. The ProgressBar can also be useful for animating the progress of a process.
CCNA Routing And Switching All In One Study Guide BOOK
2. How to add ProgressBar
You can use ProgressBar in Android Studio. It will track the progression of your app. You can add a ProgressBar to your activity by following these steps: 1. Add the ProgressBar widget in your layout file. Set the height and width of the widget to your desired values 3. The background color should be set to 4. Add the following line to the XML file < ProgressBar 5. Incorporate the next line into the XML file < ProgressBar 6. Incorporate the next line into the XML file < ProgressBar 7. Incorporate the next line into the XML file < ProgressBar 8. Add the following line to the XML file ProgressBar 9. Incorporate the next line into the XML file < ProgressBar 10. Incorporate the next line into the XML file ProgressBar 11. Add the following line to the XML file: ProgressBar 12. The following lines should be added to the XML file ProgressBar 13. The following lines should be added to the XML file: ProgressBar 14. Include the line below to the XML file
How To Configure EIGRP On Cisco Router Step By Step Guide - 4 Routers
3. How to use ProgressBar
ProgressBar is an extremely useful tool available in Android Studio. It's an excellent tool to help you in the development process. ProgressBar is an application that shows the amount of progress you've made within your project. It is found on the left-hand side of the Android Studio window. It is also possible to include the ProgressBar to your layout file, and it will automatically appear within the windows. You can change the color of the ProgressBar via its Properties menu. You can also change your color for the ProgressBar via the Properties menu.
How To Configure OSPF Single Area On 4 Routers In Cisco Packet Tracer
4. Conclusion.
A method of monitoring the current process of a project is to use the progress bar. These bars show the status of a task the user. The progress bar provides an image representation of the task that has been initiated and is in progress. This can be done by using a progress indicator in Android Studio.
How To Configure EIGRP in Packet Tracer - 3 Routers
0 notes
blogjarvisuniverse-blog · 7 years ago
Text
async task
private String url; private Uri.Builder builder; private void jsonRecycerview() {    progressDialog = new ProgressDialog(StudentActivity.this);    progressDialog.setTitle("Get Class List");    progressDialog.setMessage("Loading...");    progressDialog.setCancelable(false);    progressDialog.show();    String url = getResources().getString(R.string.main_service) + getResources().getString(R.string.student_class_by_year);    builder = new Uri.Builder().appendQueryParameter("school_id", sharedPreferences.getString("school_id", ""))            .appendQueryParameter("year", item);    Toast.makeText(StudentActivity.this, "dfg: " + item, Toast.LENGTH_LONG).show();    OnAsyncResult onAsyncResult = new OnAsyncResult() {        @Override        public void onSuccess(String result) {            Log.e("RESULT", ">>>>>> " + result);            progressDialog.dismiss();            try {                JSONObject jsonObject = new JSONObject(result);                if (jsonObject.getString("status").equals("true")) {                    JSONArray jsonArray = jsonObject.getJSONArray("data");                    for (int i = 0; i < jsonArray.length(); i++) {                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);                        StudentYear studentYear = new StudentYear();                        studentYear.setClassName(jsonObject1.getString("class_name"));                        studentYear.setClassYear(jsonObject1.getString("class_year"));                        studentYear.setTotalstudents(jsonObject1.getString("totalstudents"));                        studentYear.setClassId(jsonObject1.getString("class_id"));                        studentYearList.add(studentYear);                    }                }                recyclerView.setLayoutManager(new LinearLayoutManager(StudentActivity.this));                // mStudentClass = new ArrayList<>();                studentClassAdapter = new StudentClassAdapter(StudentActivity.this, studentYearList);                recyclerView.setAdapter(studentClassAdapter);                // studentClassAdapter.notifyDataSetChanged();                //studentClassAdapter.swap(studentYearList);             /*   runOnUiThread(new Thread(new Runnable() {                    @Override                    public void run() {*/              //  studentClassAdapter.refreshEvents(studentYearList);                    /*}                }));*/            } catch (JSONException e) {                e.printStackTrace();            }        }        @Override        public void onFailure(String result) {            progressDialog.dismiss();        }    };    GetAsyncTask getAsyncTask = new GetAsyncTask(url, onAsyncResult, builder);    getAsyncTask.execute(); } import android.net.Uri;
import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; /** * Created by prats on 3/16/2015. */ public class GetAsyncTask extends AsyncTask<Void, Void, String> {    private String url;    private OnAsyncResult onAsyncResult;    private Boolean resultFlag;    private Uri.Builder builder;    public GetAsyncTask(String url, OnAsyncResult listner, Uri.Builder builder) {        this.url = url;        this.onAsyncResult = listner;        resultFlag = false;        this.builder = builder;    }    @Override    protected void onPreExecute() {        super.onPreExecute();    }    @Override    protected String doInBackground(Void... params) {        String final_url = url.replaceAll(" ", "%20");        try {            URL url = new URL(final_url);            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            httpURLConnection.setRequestMethod("POST");            httpURLConnection.setConnectTimeout(10000);            httpURLConnection.setReadTimeout(10000);            httpURLConnection.setDoInput(true);            httpURLConnection.setDoOutput(true);           /* Uri.Builder builder = new Uri.Builder()                    .appendQueryParameter("firstParam", paramValue1)                    .appendQueryParameter("secondParam", paramValue2)                    .appendQueryParameter("thirdParam", paramValue3);*/            String query = builder.build().getEncodedQuery();            if (!TextUtils.isEmpty(query)) {                OutputStream os = httpURLConnection.getOutputStream();                BufferedWriter writer = new BufferedWriter(                        new OutputStreamWriter(os, "UTF-8"));                writer.write(query);                writer.flush();                writer.close();                os.close();            }            httpURLConnection.connect();            Log.e("Response Code:", "Response Code: " + httpURLConnection.getResponseCode());            InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());            //String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");            String response = getStringFromInputStream(in);            Log.e("Response : ", response);            resultFlag = true;            return response;        } catch (SocketTimeoutException e1) {            resultFlag = false;            return "Connection has timed out. Do you want to retry?";        } catch (Exception e) {            e.printStackTrace();            resultFlag = false;            return "Unexpected error has occurred";        }    }    @Override    protected void onPostExecute(String result) {        if (resultFlag) {            if (onAsyncResult != null) {                onAsyncResult.onSuccess(result);            }        } else {            if (onAsyncResult != null) {                onAsyncResult.onFailure(result);            }        }    }    public static String getStringFromInputStream(InputStream stream) throws IOException {        int n = 0;        char[] buffer = new char[1024 * 4];        InputStreamReader reader = new InputStreamReader(stream, "UTF8");        StringWriter writer = new StringWriter();        while (-1 != (n = reader.read(buffer)))            writer.write(buffer, 0, n);        return writer.toString();    } } public interface OnAsyncResult { public void onSuccess(String result); public void onFailure(String result); }
0 notes
javatutorial4y · 7 years ago
Photo
Tumblr media
@javacodegeeks : #Android ProgressDialog Example https://t.co/VWV4g1CXRe
0 notes
myquestionbank · 8 years ago
Text
Android questions
What are the dialog boxes that are supported in android? Explain. Android supports 4 dialog boxes: AlertDialog : An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box. ProgressDialog : This dialog box displays a progress wheel or a progress bar. It…
View On WordPress
0 notes
night-finance-site-blog · 8 years ago
Text
ポップアップウインドウ PopupWindow(this); mPopup.setWindowLayoutMode( ViewGroup.LayoutParams.WRAP_CONTENTE, ViewGroup.LayoutParams.WRAP_CONTENTE); mPopup.setContetnView(popupView); mPopup.showAsDropDown(btnPopup); mPopup.sidmiss();
リストポップアップウインドウ ListPopupwindow(this); ... mListPopup.setAdapter(adapter); ... mListPopup.setAnchorView(btnPopup); mListPopup.show();
ドラック&ドロップ iv_drop.setOnDragListener(new View.OnDraglistener() { public boolean onDrag(View v, DragEvent event) { ... ClipData clipData.getItemAt(i); Toast.maketext(getApplicationContenxt(0, ... switch (event.getAction()) { ... v.startDrag(clipData, new DragShadowBuilder(v), null 0);
src/DragView.java ... onDragEvent(DragEvent event) { ...
src/DropView.jaba ... public boolean onDragEvent(DragEvent event) { switch(event.getAction()) { case DragEvent.ACTION_DROP; ...
カレンダー表示 <CalendarView ... />
カレンダー日付変更イベント src/MainActivity.java... calView.setOnDateChangelistener(new OnDateChangeListener() { ... public void onSelecteDayChange(CalendarView view, int year, int month, int dayOfMonth) { ...
リストビュークリックイベント listView.setOnItemClickListener(new AdapterView.OnClickLidtener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
リストビュー表示位置 lv.setSelection(lv.getCount() - 1);
リストビュー先頭末尾 lv.addFotterView(mIvFooter); lv.removeFooterView(mIvFooter); return ture;
オーバースクロール setOverScrollMode(OVER_SCROLL_ALWAYS); @Override protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int ScrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
折り畳み可能リストビュー expandableView.setAdapter(adapter);
開閉リストビュークリックイベント expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @SuppressWarnings("unchecked") @Overridepublic boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
グリッドビュー gridView.setAdapter(adapter);
セルがクリック画像 gridView.setSelector(android.R.drawable.alert_light_frame);
セルクリックイベント gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
クロノメター <Chronometer ... />
クロノメター盛業 chronoMeter.setBase(SystemClock.elapsedRealtime()); chronoMeter.start(); chronoMeter.stop();
シークバー <SekBar ... />
シークバー最大値初期値 max Progress
シークバーイベント処理 @Overridepublic void onStartTrackingTouch(SeekBar seekBar) { setProgressBar IndeterminateVisibility(true); } @Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { TExtView tvprogress = (TextView) findViewById(R.id.tvProgress); tvProgress.setText(Progress + "%..."); } @Overridepublic void onStopTrackingTouch(SeekBar seekBar) { setProgressBar IndeterminateVisiblity(false); } });
スピナー <Spinner ... />
スピナー表示項目 adapter.stDropDownviewResource(android.R.layout.simple_spinner_dropdown_item); spinnerAge.setAdapter(adapter); spinnerAge.setAdapter(adapter); spinnerAge.setPrompt("年齢の選択"); spinnerAge.setSelection(3);
スピナーのドロップダウンリスト spinnerAge.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Overridepublic void onItemSelected(Adapteriew<?> parent, View view, int position, long id) ... public void onNorthSelected(AdapterView<?> parent) {
スクロールビュー追加 <ScrollView ... </ScrollView>
スクロールバー表示位置 sv.setVerticalvarPosition(ScrollView.SCROLLBAR_POSITION_LEFT);
日付ピッカー <DatePicker ... />
日付ピッカーイベント処理 datePicker.init(2013, 6, 1, mLidtener); ... public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayMonth) {
時刻ピッカー <TimePicker ... />
時刻ピッカーイベント処理 public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
数値ピッカー <NumberPicker ... />
数値ピッカー最大値最小値 numberPicker.setMaxValue(50); numberPicker.setMinValue(10);
数値ピッカーイベント処理 numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangedListener() { @Overridepublic void onValueChange(NumberPicker picker, int oldVal, int newVal) {
アラートダイヤログ setMessage("アラートダイヤログ。\nAndroid SDKポケリ") setPositiveButton("OK", new DialogIntegerface.OnClickListener() { ... .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { ... public void onClick(DialogInterface dialog, int which) { ... .setNeutralButton("Neutral", new DialogInterface.OnClickListener() { ... return builder.create(); ... newFragment.show(getSupportFragmentManager(), "showAlertDialog"); }
日付ピッカーダイヤログ return new DatePickerDialog( getActivity(), DatePickerDialog,THEME_HOLD_DARK, this, 2013, 6, 1); } @Overridepublic void onDateSet(DatePicker view, int year, int monthYear, int dayOfMonth) { ...
時刻ピッカーダイヤログ return new TimePickerDialog( getActivity(), TimeActivity(), TimePickerDialog,THEME_HOLD_DARK, this, 12, 34, true); } ... public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
プログレスダイヤログ ProgressDialog dialog = new ProgressDialog(getActivity()); dialog.setTitle("処理中..."); dialog.setMessage("少々お待ちください...'); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Notification表示 builder.setWhen(System.currentTimeMills()); ... notificationManager.notify(NOTIFY_SAMPLE, builder.build());
ステータスバー通知 icon level tickerText views
通知領域通知 autoCancel intent title text info icon
通知プロパティ defaults sound streamType argb onMs offMs pattern
消せない通知 notification.flags += Notification.FLAG_ONGOING_EVENT;
通知大きい画像 new NotificationCompat.BigPictureStyle(builder);
通知大きいテキスト bigTextNotification.bigText("文字が大きいです。"); bigTextNotification.setSummaryText("スタイルがBigTextStyle");
通知複数行 inboxStyleNotification.addLine("1"); inboxStyleNotification.addLine("2"); inboxStyleNotification.addLine("3"); inboxStyleNotification.setSummaryText("BigTextStyle");
通知UIカスタマイズ RemoteViews remoteView = new RemoteView(getPackageName(), R.layout.notification_layout); remoteView.setImageViewResource(R.id.ivIcon, R.drawable.ic_lancher); remoteView.setText(R.id.tvMessage, "..."); builder.setContent(remoteView);
通知ボタン追加 builder.addAction(android.R.drawable.stra_off, "Google", contentIntent1); ... builder.addAction(android.R.drawable.star_off, "...", contentIntent2); ... builder.addAction(android.R.drawable.star_off, "buildebox.net", contentIntent3);
スイッチ表示 <Switch ... />
スイッチイベント処理 ... sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { ... public void onChackedChanged(CompoundButton buttonView, boolean isChecked) { ...
メニューレイアウト res/menu/main.xml <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item .../> <item .../> <item .../> <groupPosition...> <item .../> <item .../> </group> </menu>
src/MainActivity.java... public boolean onCreateOptionMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem item = menu.add(Menu.NONE, MENU_SAMPLE, 600, "..."); ...
メニュー選択 ... public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { ...
ポップアップメニュ ... popupMenu.getMenuInflateer().inflate(R.menu.popup_main, popupMenu.getMenu());
ポップアップメニュ処理 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { ... public boolean onMenuItemClick(MenuItem item) { ...
コンテキストメニュ ... registerForContextMenu(lvFruits); ... public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { ...
コンテキストメニュ選択 onContextItemSelected(MenuItem item)
HOMEウィジット設定 <appwidget-provider ... </appwidget-provider>
<appwidget-provider... </appwidget-provider>
マニフェストHOMEウィジット <reciver ... <intent-filter> ... </intent-filter> <meta-data ... </reciver>
HOMEウィジット通知 ... onEnabled(Context context) { ... public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { ... public void onDeleted(Context context, int[] aqppWidgetIds) { ... public void onDisabled(Context contxt) { ... public void onReceive(Context context, Intent intent) { ...
HOMEウィジット更新 widgetManager.updateAppWidget(widget, removeViews);
HOME画面作成 ... <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" />
プリファレンス画面作成 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> ... </PreferenceScreen>
src/SettingPrefActivity.javapublic class SettingPrefActivity extends PreferenceActivity { ... addPreferencesFromResource(R.xml.setting_pref);
src/SettingPrefFragment.java public class SettingPrefFragment extends PreferenceFragment { ...
プレファレンス画面レイアウトカテゴリ <PreferenceCategory ... </PreferenceCategory> <PreferenceCategory ... </PreferenceActivity>
プリファレンスチェックボックス ... <CheckBoxPreference .../>
プリファレンスエディットテキスト <EditTextPreference .../>
プリファレンスリスト <ListPreference .../>
プリファレンス複数選択リスト <MultiSelectListPreference ... />
プリファレンススイッチ <SwitchPreference .../>
着信音通知音アラーム音 <RingtonePreference ... />
クリックイベント btn_click.setOnClickListener(new View.OnClidkListener() { ...
長押しイベント btn_longClick.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { ...
タッチイベント ... public boolean onTouchEvent(MotionEvent event) { ...
ViewPager画面切り替え <android.support.v4.view.pagerTabStrip ... />
src/MainActivity.java mViewPager.setAdapter(mPagerAdapter); ... public Fragment getItem(int position) { ... public int getCount() { ... getPageTitle(int position) ...
アプリーションアイコンナビゲーションドロワー res/layout/activity_main.xml res/layout/activity_main.xml... mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { ... public void onDrawerOpened(View drawerView) { ... public void onDrawerSlide(View drawView, float slideOffset) { ... public void onDrawerStateChange(int newState) { ... mDrawerLayout.setDrawerListener(mDrawerToggle); ... mDrawerToggle.syncstate(); ... public void onConfligurationChanged(Configration newConfig) { ... mDrawerLayout.openDrawer(Gravity.LEFT); ...
0 notes