Risipa de key_press | Programare

Programare .Net | Tehnici de programare | Tutoriale | Lectii si exemple

Risipa de key_press | Programare - Programare .Net | Tehnici de programare | Tutoriale | Lectii si exemple

Ferestre de dialog in Android

In acest episod, alcatuit din trei filme, din cauza duratei – nu am vrut sa depasesc 10-12 minute pe episod, insa am reusit sa reduc numai pana la 15 minute – voi vorbi despre ferestre de dialog si cum pot fi ele create. Voi exemplifica prin deschiderea a patru ferestre (pe rand, nu toate de-odata) care vor avea urmatorul continut:

  • O lista de checkBox-uri
  • Un indicator de progress
  • Un selector de data (DatePicker)
  • Un selector de timp (TimePicker)

Fereastra aplicatiei va arata asa:

iar la apasarea butoanelor va fi afisat un dialog corespunzator.


In prima parte voi scrie codul XML care sa imi afiseze 4 butoane. Codul XML este urmatorul:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="horizontal">
        
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" 
               android:id="@+id/btnOpenCustomDialog" android:text="Open Dialog" />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" 
            android:id="@+id/btnOpenProgress" android:text="Progress Dialog" />
    </LinearLayout>
    
    <LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="horizontal">        
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" 
            android:id="@+id/btnOpenDatePicker" android:text="Open DatePicker" />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" 
            android:id="@+id/btnOpenTimePicker" android:text="Open TimePicker" />
    </LinearLayout>
</LinearLayout>

Partea 1

La finalul acestei prime parti am vorbit despre crearea unui mesaj de tip Toast. Un Toast este un scurt text pe care il putem afisa utilizatorului – un fel de “tooltip” care contine un text scurt (nu exista limita data de OS, ci de faptul ca acest mesaj trebuie sa contina un text pe care utilizatorul sa il poata citi in maxim 2-3 secunde (nu am masurat exact durata maxima, insa e mica).
Pentru a crea un astfel de mesaj se foloseste metoda static a clasei Toast asa:

Toast.makeText(this, "Mesaj", Toast.LENGTH_SHORT).show();

In partea a doua voi trece la partea de Java si voi scrie codul care intercepteaza actiunea utilizatorului (evenumentul click). Pe undeva prin minutul 12 (cred) apare o greseala, am spus ca View este obiectul din care deriva controalele, ar fi trebuit sa spun ca este clasa din care deriva (nu se deriveaza – inheritance – un obiect, ci o clasa).
Codul care rezulta in urma acestei parti este versiunea incompleta a codului final, asa ca il voi pune in finalul acestui tutorial, dupa vizionarea partii a 3-a.

Partea 2

In aceasta parte voi implementa deschiderea ferestrelor de dialog propriu-zise. Codul complet (fisierul DemoFerestreActivity.java) este postat dupa film.
Partea 3

package eu.zeltera.demoFerestre;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class DemoFerestreActivity extends Activity implements OnClickListener {

    Button btnOpenCustomDialog;
    Button btnOpenProgress;
    Button btnOpenDatePicker;
    Button btnOpenTimePicker;

    ProgressDialog mProgress;
    int progress = 0;
    Handler mProgressHandler;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        init();
    }

    private void init() {
        btnOpenCustomDialog = (Button) findViewById(R.id.btnOpenCustomDialog);
        btnOpenProgress = (Button) findViewById(R.id.btnOpenProgress);
        btnOpenDatePicker = (Button) findViewById(R.id.btnOpenDatePicker);
        btnOpenTimePicker = (Button) findViewById(R.id.btnOpenTimePicker);

        btnOpenCustomDialog.setOnClickListener(this);
        btnOpenProgress.setOnClickListener(this);
        btnOpenDatePicker.setOnClickListener(this);
        btnOpenTimePicker.setOnClickListener(this);

    }

    public void onClick(View arg0) {

        mProgressHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                if (progress >= 100)
                    mProgress.dismiss();
                else {
                    progress++;
                    mProgress.incrementProgressBy(1);
                    mProgressHandler.sendEmptyMessageDelayed(0, 100);
                }
            }

        };

        switch (arg0.getId()) {
        case R.id.btnOpenCustomDialog:
            showDialog(0);
            break;
        case R.id.btnOpenProgress:
            showDialog(1);
            progress = 0;
            mProgress.setProgress(0);
            mProgressHandler.sendEmptyMessage(0);
            break;
        case R.id.btnOpenDatePicker:
            // showToast("btnOpenDatePicker");
            showDialog(2);
            break;
        case R.id.btnOpenTimePicker:
            // showToast("btnOpenTimePicker");
            showDialog(3);
            break;
        default:
            break;
        }

    }

    private void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected Dialog onCreateDialog(int id) {

        CharSequence[] items = { "Google", "Yahoo", "MSN" };

        switch (id) {
        case 0:
            AlertDialog ad = new AlertDialog.Builder(this)
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle("Search engines list")
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    Toast.makeText(getBaseContext(), "Ok",
                                            Toast.LENGTH_SHORT).show();
                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    Toast.makeText(getBaseContext(), "Cancel",
                                            Toast.LENGTH_SHORT).show();
                                }
                            })
                    .setMultiChoiceItems(items, new boolean[3],
                            new DialogInterface.OnMultiChoiceClickListener() {

                                public void onClick(DialogInterface dialog,
                                        int which, boolean isChecked) {
                                    Toast.makeText(getBaseContext(),
                                            "Something clicked",
                                            Toast.LENGTH_SHORT).show();

                                }
                            }).create();
            return ad;
        case 1:
            mProgress = new ProgressDialog(this);
            mProgress.setIcon(R.drawable.ic_launcher);
            mProgress.setTitle("Searching....");
            mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            return mProgress;
        case 2:
            return new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            String text = year + "/" + (monthOfYear + 1) + "/"
                                    + dayOfMonth;
                            btnOpenDatePicker.setText(text);
                        }
                    }, 2011, 1, 1);

        case 3:
            return new TimePickerDialog(this,
                    new TimePickerDialog.OnTimeSetListener() {

                        public void onTimeSet(TimePicker view, int hourOfDay,
                                int minute) {
                            String text = hourOfDay + ":" + minute;
                            btnOpenTimePicker.setText(text);
                        }
                    }, 5, 15, true);

        default:
            break;
        }

        return null;
    }
}

Va multumesc pentru vizionare si astept comentarii. Cine semnalaeaza o greseala primeste o dedicatie intr-unul din episoadele urmatoare!

Category: Uncategorized

Your email address will not be published. Required fields are marked *

*