Android开发-UI

来源:互联网 发布:c语言字母小写转换大写 编辑:程序博客网 时间:2024/05/16 16:42

1.UI(Primary)

1.Insert LinearLayout toTableLayout

<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent" android:layout_height="match_parent">

    <TableRow

        android:id="@+id/tableRow1"

        android:layout_width="fill_parent"

        android:layout_weight="1">

        <LinearLayout

            android:id="@+id/linearLayout1"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:layout_weight="1"

            android:background="@mipmap/ic_launcher">

            <TextView

                android:layout_width="fill_parent"

                android:layout_height="fill_parent"

                android:text="@string/hello_world"/>

        </LinearLayout>

        <LinearLayout

            android:id="@+id/linearLayout2"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:layout_weight="1"

            android:background="@mipmap/ic_launcher">

            <TextView

                android:layout_width="fill_parent"

                android:layout_height="fill_parent"

                android:text="@string/hello_world"/>

        </LinearLayout>

    </TableRow>


    <TableRow

        android:id="@+id/tableRow2"

        android:layout_width="fill_parent"

        android:layout_weight="1">

    </TableRow>


    <TableRow

        android:id="@+id/tableRow3"

        android:layout_width="fill_parent"

        android:layout_weight="1">

    </TableRow>

</TableLayout>


2.Toast.makeText(MainActivity.this,”ANY_STRING_IS_OK”,Toast.LENGTH_SHORT).show();


3.TextView

android:drawableBottom

android:drawableLeft

android:drawableRight

android:drawableTop         //Make picture around text

android:singleLine             //When beyond one line,……

android:autoLink                //none,web,email,phone,map,all


4.EditText login = (EditText)findViewById(R.id.login);

   String loginText = login.getText().toString();


5.Click Button

Button button1 = (Button)findViewById(R.id.button1);

   button1.setOnClickListener(new OnClickListener(){

   @override

public void onClick(View v){

EditText nicknameET = (EditText)findViewById(R.id.nickname);  //get name

String nickname = nicknameET.getText().toString();      //get input name

EditText pwdET = (EditText)findViewById(R.id.pwd);           //get pass part

String pwd = pwdET.getText().toString();                              //get input pass

Log.i(“My name is” + nickname);

}

});


6.Click RadioGroup(Single-choice)

@.xml

<RadioGroup

android:id=”@id/radioGroup1”

android:orientation=“horizontal”

android:layout_width=“wrap_content”

android:layout_heigth=“wrap_content”

<RadioButton

android:id=”@id/radio1”

android:orientation=“horizontal”

android:layout_width=“wrap_content”

android:layout_heigth=“wrap_content”/>

   </RadioGroup>

@.java

RadioGroup sex = (RadioGroup)findViewById(R.id.radioGroup1);

sex.setOnCheckedChangeListener(new OnCheckedChangeListener(){

@override

public void onCheckedChanged(RadioGroup group,int checkedId){

RadioButton r = (RadioButton)findViewById(checkedId);

r.getText();

}

});

//for(int i = 0;i<sex.getChidCount();i++){

// RadioButton r = (RadioButton)sex.getChildAt(i);

// if(r.isChecked()){r.getText();break;}}}});


7.Multiselect(CheckBox)

final CheckBox like1 = (CheckBox)findViewById(R.id.like1);

like1.setOnCheckedChangeListener(new OnCheckedChangeListener(){

@override

public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){

if(like1.isChecked()){like1.getText();}

}});


8.ImageView

android:adjustViewBounds              //Keep size rate

android:scaleType      //matrix,fitXY,fitStart,fitCenter,fitEnd,center,centerCrop


9.Spinner

<Spinner

android:prompt=“@string/info”                          //tip

android:entries=“@array/ctype”

android:layout_height=“wrap_content”

android:layout_height=“wrap_content”>

</Spinner>

@res\values

<?xml version=“1.0” encoding=“utf-8”?>

<resources>

<string-array name =“ctype”>

<item>123</item>

<item>234</item>

<item>345</item>

</string-array>

</resource>

@.java

Spinner spinner = (Spinner)findViewById(R.id.spinner1);

spinner.getSelectedItem();


spinner.setOnItemSelectedListener(new onItemSelectedListener(){

@override

public void onItemSelected(AdapterView<?> parent,View arg1,int pos,long id){

String result = parent.getItemAtPosition(pos).toString();

Log.i(“Spinner”,result);

}

@override

public void onNothingSelected(AdapterView<?> arg0){}

}

});


10.Adapter

When you create an Adapter,you can use the resource files of array or create in java files.

1>ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(

this,R.array.ctype,android.R.layout.simple_dropdown_item_1line);

//Create an Adapter

String[] ctype = new String[]{“123”,”234”,”345”};

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ctype);

2>adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

3>spinner.setAdapter(adapter);


11.ListView

@.xml

simple_list_item1                  //Every list is text

simple_list_item2                  //TextSize bigger

simple_list_item_checked           //checked for each list 

simple_list_item_multiple_choice   //multiple_choice for each list

simple_list_item_simple_choice     //simple_choice for each list


android:divider                    //You can use color or Drawable

android:dividerHeight      

android:entries

android:footerDivedersEnable       //true(need use addFooterView()) or false

android:headerDivedersEnable       //true(need use addHeaderView()) or false


@.java(method)

final ListView listView = (ListView)findViewById(R.id.listView1);

listView.addHeaderView(line());    //set heaer_view

ArraryAdapter<CharSequence> adapter = ArraryAdapter.createFromResource(

this,R.array.ctype,android.R.layout.simple_list_item_checked);         

listView.setAdapter(adapter);

listView.addFooterView(line());

listView.setOnItemClickListener(new OnItemClickListener(){

@override

public void onItemClick(AdapterView<?> parent,View arg1,int pos,long id){

String result = parent.getItemAtPosition(pos).toString();

Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();

}

});


@.java(extend)

public class MainActivity extends ListActivity{

@override

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

/////////////////////////

String[] ctype = new String[]{"123","234","345"};

ArraryAdapter<String> adapter = new ArraryAdapter<String>(this,

android.R.layout.simple_list_item_single_choice,ctype);

setListAdapter(adapter);

}

}


@override

protected void onListItemClick(ListView l,View v,int p){

super.onListItemClick(l,v,position,id);

String result = l.getItemAtPosition(position).toString();

Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();

}

}


12.Time

@.xml

<DatePicker

android:layout_width = “wrap_content”

android:layout_height = “wrap_content”/>

<TimePicker

android:layout_width = “wrap_content”

android:layout_height = “wrap_content”/>

@.java

DatePicker datepicker  = (DatePicker)findViewById(R.id.datePicker1);

TimePicker timepicker  = (TimePicker)findViewById(R.id.timePicker1);

time picker.setIs24HourView(true);


Calendar calendar = Calendar.getInstance();

year = calendar.get(Calendar.YEAR);

month = calendar.get(Calendar.MONTH);

day = calendar.get(Calendar.DAY_OF_MONTH);

hour = calendar.get(Calendar.HOUR_OF_DAY);

minute = calendar.get(Calendar.DAY_OF_MINUTE);


datePicker,init(year,month,day,new OnDateChangedListener(){

@override

public void onDateChanged(DatePicker arg0,int year,int month,int day){

MainActivity.this.year = year;

MainActivity.this.month = month;

MainActivity.this.day = day;

show(year,month,day,hour,minute);

}

});


timePicker.setOnTimeChangedListener(new OnTimeChangedListener(){

@override

public void onTimeChangedListener(TimePicker view,int hourOfDay,int minute){

MainActivity.this.hour = hourOfDay;

MainActivity.this.minute = minute;

show(year,month,day,hourOfDay,minute);

}

});


private void show(int year,int month,int day,int hour,int minute){

String str = year+"-"+(month+1)+"-"+day+"-"+hour+":"+minute;

Toast.makeText(this,str,Toast.LENGTH_SHORT).show();

}


13.Chronometer

@.xml

<chronometer

android:text = "Chronometer"

android:layout_width = "wrap_content"

android:layout_heigth = "wrap_content"/>


final Chronometer ch = (Chronometer)findViewById(R.id.chronometer1);

ch.setOnChronometer(SystemClock.elapsedReadtime());

ch.setFormat("use time:%s");

ch.start();

ch.setOnChronometerTickListener(new OnChronometerTickListener(){

@override

public void onChronometerTick(Chronometer chronometer){

if(SystemClock.elapsedRealtime()-ch.getBase()>=10000){

ch.stop();

}

}

});



14.example

e.g.1 ImageButton with Mouse Click

@.xml

android:src = "@drawable/button_state"

android:background = “#0000”  

(As usual,ImageButton will come with grey background,#0000 means black Transparent) 

@button_state.xml

<?xml version = "1.0" encoding = "utf-8">

<selector

      xmlns:android:"http://schemes.android.com/apk/res/android">

<item android:state_pressed = "true" android:drawable = "@drawable/start_b"/>

<item android:state_pressed = "false" android:drawable = "@drawable/start_a"/>

</selector>


e.g.2 ListView with icon

@.xml

<?xml version = "1.0" encoding = "utf-8">

<LinearLayout

      xmlns:android:"http://schemes.android.com/apk/res/android"

      android:orientation = "horizontal"

      android:layout_width = "match_parent"

      android:layout_height = "match_parent">

<ImageView

android:paddingRight = "10px"

android:paddingTop = "20px"

android:paddingBottom = "20px"

android:adjustViewBounds = "true"

android:maxWidth = "72px"

android:maxHeight = "72px"

android:layout_width = "wrap_content"

  android:layout_height = "wrap_content"/>

<TextView

android:layout_width = "wrap_content"

  android:layout_height = "wrap_content"

android:padding = "10px"

android:layout_gravity = "center"/>

</LinearLayout>

@MainActivity.class

ListView listview = (ListView)findViewById(R.id.listView1);

int[] imageld = new int[]{R.drawable.img01,R.drawable.img02,R.drawable.img03,

R.drawable.img04,R.drawable.img05,R.drawable.img06,

R.drawable.img07,R.drawable.img08};

String[] title = new String[]{"keep secret","security","system setting","Interent,"My 

document","GPS","Music","E-mail"};

List<Map<String,Object>>listItems = new ArraryList<Map<String,Object>>();

for(int i = 0;i < imageId.length; i++){

Map<String,Object> map = new HashMap<String,Object>();

map.put("image",imageId[i]); 

map.put("title",title[i]);

listItems.add(map);

}

SimpleAdapter adapter = new SimpleAdapter(this,listItems,

R.layout.items,new String[]{"title","image"},new int[]{R.id.title,R.id.image});

listView.setAdapter(adapter);


e.g.3 (3 shoes)

image1.setImageDrawable(getResources().getDrawable(imageIds[0]));

image1.setAlpha(100);            //set alpha value

int[] imageIds = new int[] { R.drawabe.shoe_ok,R.drawable.shoe_sorry,

R.drawable.shoe_sorry};




2.UI(Senior)

1.AutoCompleteTextView

android:completionHint

android:completionThreshold                  //when type in how many characters,hint

android:dropDownHeight

android:dropDownHorizontalOffset

android:dropDownWidth

android:popupBackground


private static final String[] COUNTRIES = new String[] {

“123”,”234”,”456”,”567”};

AutoCompleteTextView textView = (AutoCompleteTextView)findViewById

(R.id.autoCompleteTextView1);

ArrayAdapter<String> adapter = new ArraryAdapter <String>(this,

android.R.layout.simple_dropdown_item_1line ,COUNTRIES);

textView.setAdapter(adapter);

Button button = (Button)findViewById(R.id.button1);

button.setOnClickListener( new OnClickListener(){

@override

public void onClick(View v){

Toast.makeText(MainActivity.this,textView.getText().toString(),

Toast.LENGTH_SHORT).show();

}

}):


2.ProgressBar

android:max

android:progress

android:progressDrawable

style = “@android:style/Widget.ProgressBar.Horizontal”

style = “@android:style/Widget.ProgressBar.Large”

style = “@android:style/Widget.ProgressBar.Small”

style = “?android:attr/progressBarStyleLarge”

style = “?android:attr/progressBarStyleSmall”

style = “?android:attr/progressBarStyleHorizontal”

private ProgressBar horizonP;

private ProgressBar circleP;

private int mProgressStatus = 0;

private Handler mHandler;


horizonP = (ProgressBar)findViewById(R.id.progressBar1);

circleP = (ProgressBar)findViewById(R.id.progressBar2);

mHandle = new Handler(){

@override

public void handleMessage(Message msg){

if(msg.what == 0x111){

horizonP.setProgress(mProgressStatus);       //update progressBar

} else {

Toast.makeText(MainActivity.this,”complete”,Toast.LENGTH_SHORT)

.show();

horizonP.setVisibility(View.GONE);

circleP.setVisibility(View.GONE);                    //close progressBar

}

}

};


new Thread(new Runnable(){

public void run(){

while(true){

mProgressStatus = doWork();                        //get percent of time waste

Message m = new Message():

if(mProgessStatus<100){

m.what = 0x111;

mHandler.sendMessage(m);

} else {

m.what = 0x110;

mHandler.sendMessage(m);

break;

}

}

}


private int doWork(){

mProgressStatus+=Math.random()*10;

try{

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

return mProgressStatus;

}

}).start();


3.SeekBar

final TextView result = (TextView)findViewById(R.id.textView1);

seeker = (SeekBar)findViewById(R.id.textView1);

seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

@override

public void onStopTrackingTouch(SeekBar seekBar){

//performance

}

@override

public void onStartTrackingTouch(SeekBar seekBar){

//performance

}

@override

public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser){

result.setText(“value”+progress);

}

});


4.RatingBar

android:isIndicator    //true:cannot change

android:numStars     //limit the number of stars

android:rating           //set as default

android:stepSize      //default is 0.5

ratingBar = (RatingBar)findViewById(R.id.ratingBar1);

Button button = (Button)findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener(){

@override

public void onClick(View v){

int result = ratingBar.getProgress();

float rating = ratingBar.getRating();

floating step = ratingBar.getStepSize();

Log.i(“Rating:”,”step = ”+step+” result = ”+result+” rating : ”+rating);

Toast.makeText(MainActivity.this,”you got”+rating+”stars”,

Toast.LENGTH_SHORT).show();

}

});


5.TabHost&TabWidget&FrameLayout

@.xml

<?xml version = “1.0” encoding = “utf-8”>

<TabHost xmlns:android=“http://schemas.android.com/apk/res/android”

android:id=“@android:id/tabhost”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”>

<LinearLayout

android:orientation = “vertical”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”>

<TabWidget

android:id=“@id/tabs”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”>

<FrameLayout

android:id=“@id/tabcontent”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”>

</FrameLayout>

</LinearLayout>

</TabHost>




@tab1.xml

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

android:id=“@id/LinearLayout01”

android:orientation=“vertical”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

<TextView 

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”

android:text=“nice is not simple”/>

<TextView 

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”

android:text=“grass with ling”/>

</LinearLayout>

private TabHost tabHost;

tabHost = (TabHost)findViewById(android.R.id.tabhost);

tabHost.setup();


LayoutInflater inflater = LayoutInflater.from(this);

inflater.inflate(R.layout.tab1,tabHost.getTabContentView());

inflater.inflate(R.layout.tab1,tabHost.getTabContentView());

tabHost.addTab(tabHost.newTabSpec(“tab01”))

.setIndicator(“unreceived call”);

.setContent(R.id.LinearLayout01);

tabHost.addTab(tabHost.newTabSpec(“tab02”))

.setIndicator(“received call”);

.setContent(R.id.LinearLayout02);


6.ImageSwitcher

<?xml version = “1.0” encoding = “utf-8”>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android"

android:orientation = “horizontal”

android:layout_width = “fill_parent”

android:layout_height = “fill_parent”

android:id = “@+id/llayout”

android:gravity = “center”

<Button

android:text = “preview”

android:id = “@+id/button1”

android:layout_width = “wrap_content”

android:layout_height = “wrap_content”/>

<ImageSwitcher

android:layout_width = “wrap_content”

android:layout_height = “wrap_content”

android:id = “@+id/imageswitcher1”

android:gravity = “center”

/>

<Button

android:text = “next”

android:id = “@+id/button2”

android:layout_width = “wrap_content”

android:layout_height = “wrap_content”/>

</LinearLayout>


private int[] imageId = new int[] { R.drawable.img01 , R.drawable.img02,

R.drawable.img03 , R.drawable.img04 , R.drawable.img05};

private int index = 0;

private ImageSwitcher imageSwitcher;


imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);

imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));

imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));

imageSwitcher.setFactory(new ViewFactory(){

@override

public View makeView(){

imageView = new ImageView(MainActivity.this);

imageView.setScaleType(imageView.ScaleType.FIT_CENTER);

imageView.setLayoutParams(new ImageSwitcher.LayoutParams(

LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

return imageView;

}

});

imageSwitcher.setImageResouces(imageId[index]);


Button up = (Button)findViewById(R.id.button1);

Button down = (Button)findViewById(R.id.button2);

up.setOnCLickListener(new OnClickListener(){

@override

public void onClick(View v){

if(index > 0)

index—— ;

else

index = imageId.length - 1;

      imageSwitcher.setImageResource(imageId[index]);

}

});

down.setOnClickListener(new OnClickListener(){

@override

public void onClick(View v){

if(index < imageId.length - 1)

index++;

else

index = 0;

    imageSwitcher.setImageResource(imageId[index]);

}

});


7.GridView

android:columnWidth

android:horizontalSpacing     //

android:numColumns            //if only has 1 column,please user list view

android:stretchMode             //none,spacingWidth,columnWidth,spacingWidthUnifrom

android:verticalSpacing         //size between |(vertical)


GridView gridview = (GridView)findViewById(R.id.gridView1);

int[] imageId = new  int[]{ R.drawable.img01 , R.drawable.img02};

String[] title = new String[] {“123”,”234”};

List<Map<String,Object>> listItems = new ArraryList<Map<String,Object>>();

for(int i = 0; i <imageId.length,i++){

Map<String,Object> map = new HashMap<String,Object>();

map.put(“image”,imageId[i]);

map.put(“title”,title[i]);

listItems.add(map);

}

SimpleAdapter adapter = new SimpleAdapter(this,

listItems,

R.layout.items,

new String[]{“title”,”image”},

new int[] {R.id.title,R.id.image}

);

gridview.setAdapter(adapter);


//If you do not want to present characters,you can use BaseAdapter

BaseAdapter adapter = new BaseAdapter(){

@override

public View getView(int position,View convertView,ViewGroup parent){

ImageView imageView;

if(convertView == null){

imageview = new ImageView(MainActivity.this);

imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

imageview.setPadding(5,0,5,0);

} else {

imageview = (ImageView)convertView;

}

imageview.setImageResource(imageId[position]);

return image view;

}

@override

public long getItemId(int position){

return position;

}


@override

public Object getItem(int position){

return position;

}


@override

public int getCount(){

return imageId.length;

}

};

gridview.setAdapter(adapter);

8.Gallery

android:animationDuration          //time of change picture’s cartoon

android:spacing                           //distance between them

android:unselectedAlpha             //Alpha


Gallery gallery = (Gallery)findViewById(R.id.gallery1);


@res\values attire.xml

<resources>

<declare-styleable name = “Gallery”>

<attr name = “android:galleryItemBackground” />

<declare-styleable>

</resources>



BaseAdapter adapter = new BaseAdapter(){

@override

public View getView(int position,View convertView,ViewGroup parent){

ImageView imageview;

if(convertView == null) {

imageview = new ImageView(MainActivity.this);

imageview.setScaleType(ImageView.ScaleType.FIT_XY);

imageview.

setLayoutParams(new Gallery.LayoutParams(180,135));

TypedArrary typedArrary = obtainStyledAttributes(R.styleable.Gallery);

imageview.setBackgroundResource(typedArrary.getResourceId(

R.styleable.Gallery_android_galleryItemBackground,0));

imageview.setPadding(5,0,5,0);

} else {

imageview = (ImageView)convertView;

}

imageview.setImageResource(imageId(position));

return imageview;

}

@override

public long getItemId(int position){

return position;

}

@override

public Object getItem(int position){

return position;

}

@override

public int getCount(){
return imageId.length;

}

};


gallery.setAdapter(adapter);

gallery.setSelection(imageId.length/2);

gallery.setOnItemClickListener(new OnItemClickListener(){

@override

public void onItemClick(AdapterView<?> parent,View view,int position,long id){

Toast.makeText(MainActivity.this,”you choose ”+String.valueOf(position),

Toast.LENGTH_SHORT).show();

}

});


9.Notification & Notification Manager

final NotificationManager notificationManager = 

(NotificationManager)getSystemService(NOTIFICATION_SERVICE);


Button button1 = (Button)findViewById(R.id.button1);

button1.setOnClickListener(new OnClickListener(){

@override

public void onClick(View v){

Notification notify = new Notification();

notify.icon = R.drawable.advise;

notify.tickerText = “My Frist notice”

notify.when = System.currentTimeMillis();

notify.setLatestEventInfo(MainActivity.this,”None”,”Day day up”,null);

notificationManager.notify(NOTIFYID_1,notify);

Notification notify1 = new Notification(R.drwaable.advise2,

“2nd notice”,System.currentTimeMillis());

notify1.flags|=Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(MainActivity.this,ContentActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);

notify1.setLatestEventInfo(MainActivity.this,”note”,”for more”,pendingIntent);

notificationManager.notify(NOTIFYID_2,notify1);

}

});



<uses-permission android name = “android.permission.FLASHLIGTH”/>

<uses-permission android name = “android.permission.VIBRATE”/>


<activity android:name = “ContentActivity”

android:label = “For more content”

android:theme = ‘@android:style/Theme.Dialog“/>


Button button2 = (Button)findViewById(R.id.button2);

button2.setOnClickListener(new OnClickListener(){

@override

public void onClick(View v){

notificationManager.cancel(NOTIFYID_!);

notificationManager.cancelAll();

}

});


10.AlertDialog.class

setButton()

DialogInterface.BUTTON_POSITIVE //sure

.BUTTON_NEGATIVE //cancel

.BUTTON_NEUTRAL //nothing

AlertDialog.Builder.class

setMessage(CharSequence message)

setNegativeButton()

setPositiveButton()

setNeutralButton()

setItem()

setSingleChoiceItems()

setMultiChoiceItems()


@MainActivity.java

//Dialog

Button button1 = (Button)findViewById(R.id.button1);

button1.setOnClickListener(new View.OnClickListener(){
@override

public void onClick(View v)P

AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();

alert.setIcon(R.drawable.advise);

alert.setTitle(“System show:”);

alert.setMessage(“A Dialog with 3 Buttons!”);

//cancel

alert.setButton(DialogInterface.BUTTON_NEGATIVE,”cancel”,newOnClickListener(){

@override

public void onClick(DialogInterface dialog,int which){

Toast.makeText(MainActivity.this,”you cancelled”,

Toast..LENGTH_SHORT).show();

}

});

alert.setButton(DialogInterface.BUTTON_POSITIVE,”positive”,newOnClickListener(){

@override

public void onClick(DialogInterface dialog,int which){

Toast.makeText(MainActivity.this,”you positived”,

Toast..LENGTH_SHORT).show();

}

});

alert.setButton(DialogInterface.BUTTON_NEUTRAL,”neutral”,newOnClickListener(){

@override

public void onClick(DialogInterface dialog,int which){

Toast.makeText(MainActivity.this,”you neutralled”,

Toast..LENGTH_SHORT).show();

}

});


//Dialog with list

Button button2 = (Button)findViewById(R.id.button2);

button2.setOnClickListener(new View.OnClickListener(){

@override

public void onClick(View v){

final String[] items = new String[]{“123”,”234”};

Builder builder = new AlertDialog.Builder(MainActivity.this);

builder.setIcon(R.drawable.advise1);

builder.setTitle(“Please the sports you like”);

builder.setItems(items,new OnClickListener(){

@override

public void onClick(DialogInterface dialog,int which){

Toast.makeText(MainActivity.this,

you choose ”+items[which],Toast.LENGTH_SHORT).show();

}

});

builder.create().show();

}

});


private boolean[] checkedItems; //record status of lists

private String[] items; //each list comes with


//Dialog with RadioButton

Button button3 = (Button)findViewById(R.id.button3);

button3.setOnClickListener(new View.OnClickListener(){

@override

public void onClick(View v){

final String[] items = new String[] {“123”,”234”};

Builder builder = new AlertDialog.Builder(MainActivity.this);

builder.setIcon(R.drawable.advise2);

builder.setTitle(“Please choose games you like:”);

builder.setMultiChoiceItems(items,checkedItems,

new OnMultiChoiceClickListener(){

@override

public void onClick(DialogInterface dialog,int which,boolean isChecked){

checkedItems[which]=isChecked;

}

});

builder.setPositiveButton(“make sure”,new OnClickListener(){

@override

public void onClick(DialogInterface dialog,int which){

String result = “”;

for(int i = 0;i <checkedItems.length; i++){

if(checkedItems[i]){

result+=items[i]+”,”;

}

}

if(“!”.equals(result)){

result = result.substring(0,result.length()-1);

Toast.makeText(MainActivity.this,

“you choose ”+result,Toast.LENGTH_LONG).show();

}

}

});

builder.create().show();

}

});


//finish():end back to Main

11.Dialog with list of icons

@item.xml

<?xml version = “1.0” encoding = “utf-8”?>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

    android:orientation = “horizontal”

    android:layout_width = “match_parent”

    android:layout_height = “match_parent”>

<ImageView

android:id = “@+id/image”

android:paddingLeft = “10px”

android:paddingTop = “20px”

android:paddingBottom = “20px”

android:adjustViewBounds = “true”

android:maxWidth = “72px”

android:maxHeight = “72px”

android:layout_height = “wrap_content”

android:layout_width = “wrap_content”/>

<TextView

android:layout_width = “wrap_content”

android:layout_height = “wrap_content”

android:padding = “10px”

android:layout_gravity = “center”

android:id = “@+id/title”/>

</LinearLayout>


@MainActivity.java

int[] imageId = new int[] {R.drawable.img01,R.drawable.img02};

final String[] title = new String[] {“1”,”2”};

List<Map<String,Object>> listItems = new ArraryList<Map<String,Object>>();

for(int i = 0 ;i < imageId.length, i ++){

Map<String,Object> map = new HashMap<String,Object>();

map.put(“image”,imageId[i]);

map.put(“title”,title[i]);

listItems.add(map);

}

final SimpleAdapter adapter = new SimpleAdapter(this,listItems,R.layout.items,new String[]{“title”,”image”},new int[]{R.id.title,R.id.image});


Button button1 = (Button)findViewById(R.id.button1);

button1.setOnClickListener(new View.OnClickListener(){

@override

public void onClick(View v){
Builder builder = new AlertDialog.Builder(MainActivity.this);

builder.setIcon(R.drawable.advise);

builder.setTitle(“Setting:”);

builder.setAdapter(adapter,new OnClickListener(){

@overrie

public void onClick(DialogInterface dialog,int which){

Toast.makeText(MainActivity.this,

“you choose”+title[which],LENGTH_SHORT).show();

}

});

builder.create().show();

}

});

0 0
原创粉丝点击