You are on page 1of 42

Thit k giao din trn Android - Trong Android, dng Activity hin th mn hnh.

. - Mi activity s cha cc View theo dng cu trc cy, ngha l mt Layout gc cha cc view/layout con bn trong hoc ch c 1 view duy nht. (lu Layout cng l mt view nh) - C th thit k giao din trong code java hoc trong file xml trong th mc layout. 1. Layout mu ca helloworld HTML Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=@string/hello /> </LinearLayout>

2. Mt s thuc tnh c bn - Layout_width, layout_height: chiu rng ca view (fill_parent l to bng kch thc ca layout cha view ny, wrap_content l va ni dung cn hin th ca view) - Orientation: vi LinearLayout, vic sp xp cc view l nm k nhau theo hng ngang hoc hng dc, ta khai bo orientation chn sp theo kiu no (horizontal/vertical) - Gravity: thuc tnh ny qui nh cc view nm bn trong layout s t theo v tr no so vi layout(trung tm, tri , phi, trn di) - Weight: cc view phan chia t l din tch hin th trn mn hnh (t l tnh theo weight ca tng view trn tng s weight, cc view ko khai bo weight th s xem qua width v height) 4. Giao din vi LinearLayout * Vi LinearLayout (LL), cc view bn trong n c t k nhau theo hng ngang hoc hng dc (cn lu c im ny)

* Vi v d va ri, ta thy cch phn tch nh sau: - Nguyn tc ch yu l phn nhm cc View lin tip k nhau (nh 3 TextView k nhau theo hng dc hoc hng ngang trong v d trn) vo trong mt LL, phn r t ln n nh. - Nh vy mn hnh gm 1 LL ln bao bn ngoi, nhn thy bn trong chia thanh 2 phn trn di r rng vy thuc tnh ca LL ny l dng dc, sau chia i ra v phn tch tip. - Phn bn trn li chia thnh 2 na theo hng ngang l mt LL dng ngang, li chia i: mt bn l 1 ImageView (v ch c 1 view nn ko cn b vo trong LL), mt bn li l 1 LL cha 3 TextView theo hng dc. - Na bn di ta thy r rng cha 3 TextView k nhau theo hng ngang cho vo 1 LL dng ngang l xong. J FrameLayout: cc view bn trong c qui nh v tr bng khong cch so vi bin tri v trn so vi layout, cc view c th ln nhau. - RelativeLayout: cc view c thit k da trn quan h gia chng vi nhau v vi layout cha chng. - AbsoluteLayout: dnh cho bn no lm nhiu vi C#, nhng ko khuyn khch vi Android nh. - Hn ch sau ca cy - Vi cc Layout phc tp, ng dng RelativeLayout - Nn chn vo d liu tm xem trc layout hin th ra sao bn tab layout (trong eclipse), nhng xong ri th nh xa d liu tm i. - FrameLayout c vn vi background - Mun tm thuc tnh g, bm android: ri i suggestion s ra xem. Phn mm ly thng tin v hin th cc File nh trong th SD card u tin chng ta ni qua v th SD Card, th SD Card trong in thoi th khng cn xa l g vi chng ta, nhng trong thit b m phng th th SD Card c m phng v s dng nh th no? Th SD Card dng cho b m phng s c to khi chng ta khi to AVD, nh trong my mnh s nm : C:\Documents and Settings\Trungh0\.android\avd\Avd_2.2.avd vi trn sdcard.img. Chng ta c th m file ny, thm xa sa i d liu thng qua chng trnh UntraIso hoc thng qua chng trnh h tr ca Android l File Eplorer. Tip theo l n vic lp trnh: Chng ta s vit ctrinh c ton b file nh trong th nh v hin th nh cng nh tn file nh ln mn hnh Android di dang 1 GridView (l mt kiu hin th cc List Item theo dng mng li)

B1: Khi to Project: name: LoadImg, MainActivity: mainActivity B2:Thit k giao din: -Chng ta cn 1 file xml cha giao din bao gm 1 ImageView v 1 TextView hin th nh v tn nh, to file img.xml v code nh sau: PHP Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <ImageView android:src="@drawable/icon" android:layout_width ="150dp" android:id="@+id/imageView1" android:layout_height="150 dp"></ImageView> <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_ content"></TextView> </LinearLayout> -File main.xml s cha 1 GridView show nh v tn nh ln (chng ta s Grid view hin th theo 2 ct) Code: ch dng numberColumn PHP Code: <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/andr oid" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="2" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" /> B3:To file Item.java, class ny cha cc i tng lu thuc tnh ca nh: PHP Code:

package trungh0.study; import android.graphics.Bitmap; public class Item { String name; Bitmap img; public Item(String name,Bitmap img){ this.name=name; this.img=img; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public Bitmap getImg(){ return img; } public void setImg(Bitmap img){ this.img=img; } } B4:To file Image_Adapter.java to mt Adapter truyn d liu t mt ArrayList cc Item vo GridView Code: PHP Code: package trungh0.study; import java.util.List; import import import import import import import android.content.Context; android.view.LayoutInflater; android.view.View; android.view.ViewGroup; android.widget.BaseAdapter; android.widget.ImageView; android.widget.TextView;

public class Image_Adapter extends BaseAdapter { private Context mContext;

private List<Item> list_item; public Image_Adapter(Context c,List<Item> obj) { mContext = c; list_item=obj; } public int getCount() { return list_item.size(); } public Object getItem(int position){ return null; } public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v; if(convertView==null){ LayoutInflater inflater = LayoutInflater.from(mConte xt); v = inflater.inflate(R.layout.img, null); TextView tv = (TextView)v.findViewById(R.id.textView1 ); tv.setText(list_item.get(position).getName()); ImageView iv = (ImageView)v.findViewById(R.id.imageV iew1); iv.setImageBitmap(list_item.get(position).getImg()); } else { v = convertView; } return v; } } Ch : Hm getCount() khi chng ta return li gi tr bao nhiu th sau GridView s hin th by nhiu Item, y mnh cho hin th ht nhng nh

no c c nn list.getsize() B5: Quan trng nht l y, chng ta c nhim v phi c thng tin cc file nh trong th nh lu chng trong 1 list, sau s dng Adapter y chng vo GridView Code c cc file nh trong th nh: PHP Code: Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String[] cursor_cols = { MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA }; //String where = MediaStore.Images.Media. + " =1"; Cursor cursor = getContentResolver().query(uri, curs or_cols, null, null, null); int i=0; while (i<cursor.getCount()){ cursor.moveToNext(); String path = cursor.getString(cursor.getColumnI ndexOrThrow(MediaStore.Images.Media.DATA)); Bitmap img=BitmapFactory.decodeFile(path); String name= cursor.getString(cursor.getColumnIn dexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)); Log.d("TB:" , path +" "+name); list.add(new Item(name,img)); i++; } chng ta cng c th lm tng t vi cc loi file media khc nh music, video thng qua th vin MediaStore. Tuy nhin mt vn ny sinh ra l s thng mt vi giy cho vic c v hin th cc file nh ln mn hinh Android, khi ngi dng m ng dng s d tng my b treo. Cch gii quyt l ta s a cng vic mt thi gian ny vo mt thread chy ngm, v trn mn hnh chnh s hin th mt ProgessDialog bo hiu chng trnh vn ang chy. Khi no d liu c load xong, Progess Dialog ny s bin mt v hnh nh ca chng ta s hin th. Chng ta s code nh sau: PHP Code:

package trungh0.study; import java.util.ArrayList; import java.util.List; import import import import import import import import import import import import android.app.Activity; android.app.ProgressDialog; android.database.Cursor; android.graphics.Bitmap; android.graphics.BitmapFactory; android.net.Uri; android.os.Bundle; android.os.Handler; android.os.Message; android.provider.MediaStore; android.util.Log; android.widget.GridView;

public class mainActivity extends Activity { /** Called when the activity is first created. */ private List<Item> list; private ProgressDialog pd; private GridView gv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gv=(GridView)findViewById(R.id.gridview); list=new ArrayList<Item>(); pd = ProgressDialog.show(this, "Loading... ait!!!", true,false); myThread mt=new myThread(); Thread th=new Thread(mt); th.start(); } public class myThread implements Runnable{ String output=""; @Override public void run() { // TODO Auto-generated method stub Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_U RI; String[] cursor_cols = { ", "Please W

MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA }; //String where = MediaStore.Images.Media. + " =1"; Cursor cursor = getContentResolver().query(uri, curs or_cols, null, null, null); int i=0; while (i<cursor.getCount()){ cursor.moveToNext(); String path = cursor.getString(cursor.getColumnI ndexOrThrow(MediaStore.Images.Media.DATA)); Bitmap img=BitmapFactory.decodeFile(path); String name= cursor.getString(cursor.getColumnIn dexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)); Log.d("TB:" , path +" "+name); list.add(new Item(name,img)); i++; } handler.sendEmptyMessage(0); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { pd.dismiss(); Image_Adapter ia=new Image_Adapter(getApplic ationContext(), list); gv.setAdapter(ia); } }; } } Bc 6: nh nhng nht, save li, dng untralIso add thm vo th nh nh vi em hotgirl, Ctrl+F11 v chim ngng thi Kt qu n :

Kim Na Na nh

Lp trnh Android c bn: x l vi GridView Ti mun hin th mt lot cc nh c trong th mc ln mt gridview xem tng th. Khi , ti dng Gridview n gin hin th nh sau: 1. Chun b mt s nh cn hin th. 2. Ta s to mt gridview nh mt ma trn hin th tng nh trn cc trong main.xml nh sau: <GridView android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" //s ct.T ng ph thuc vo s image c trong folder android:verticalSpacing="10dp" //khong cch theo chiu dc gia hai nh lin tip

android:horizontalSpacing="10dp" //khong cch theo chiu ngang ca hai nh k nhau android:stretchMode="columnWidth" android:gravity="center" /> 3. Trong Activity ta s s li code nh sau: public class GridViewActivity extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; }

// references to our images private Integer[] mThumbIds = { R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 }; } } OK, vy l xong. Ta c kt qu chy nh sau:

Download ton b code ti y.

Lp trnh vi ListView bi: Lm ng dng hin th List Phone Book: B1: To file phonebook.xml trong th mc res/layout v to ra giao din ca mt hng trong list Phone Book bao gm cc item: 1 ImageView cha Avatar ca ngi dng, 3 TextView cha tn, s in thoi v Email ngi dng.

Ta lm nh sau: Code: Code: <?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" > <ImageView android:id="@+id/imgAvatar" android:layout_width="70dip" android:layout_height="70dip" android:scaleType="fitCenter" android:src="@drawable/icon" /> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/tvName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" /> <TextView android:id="@+id/tvPhone" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView

android:id="@+id/tvEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> B2: To giao din cho file main.xml: Cha mt listview hin th cc PhoneBook. Chng ta lm nh sau: Code: Code: <?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"> <ListView android:id="@+id/listPhone" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> B3: Vo src/name package/ to file PhoneBook.java: L file nh ngha mt class PhoneBook vi cc thuc tnh: mAvatar, mPhone, mName, mEmail : Code: Code: public class PhoneBook { private Bitmap mAvatar; private String mName; private String mPhone; private String mEmail; public PhoneBook(Bitmap avatar, String name, String phone, String email) { mAvatar = avatar; mName = name; mPhone = phone; mEmail = email;

} public void setAvatar(Bitmap avatar) { mAvatar = avatar; } public Bitmap getAvatar() { return mAvatar; } public void setName(String name) { mName = name; } public String getName() { return mName; } public void setPhone(String phone) { mPhone = phone; } public String getPhone() { return mPhone; } public void setEmail(String email) { mEmail = email; } public String getEmail() { return mEmail; } } B4: Vo src/name package/ to file PhoneBookAdapter.java: to mt lp Adapter truyn d liu t mt ArrayList vo ListView: Code: Code: package trungh0.study; import import import import import import import import java.util.List; android.content.Context; android.view.LayoutInflater; android.view.View; android.view.ViewGroup; android.widget.BaseAdapter; android.widget.ImageView; android.widget.TextView;

public class PhoneBookAdapter extends BaseAdapter { private Context mContext; private List<PhoneBook> mListPhoneBook; public PhoneBookAdapter(Context context, List<PhoneBook> list) { mContext = context; mListPhoneBook = list; } @Override public int getCount() { return mListPhoneBook.size(); } @Override public Object getItem(int pos) { return mListPhoneBook.get(pos); } @Override public long getItemId(int pos) { return pos; } @Override public View getView(int pos, View convertView, ViewGroup parent) { // get selected entry PhoneBook entry = mListPhoneBook.get(pos); // inflating list view layout if null if(convertView == null) { LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(R.layout.phonebook.xml, null); } // set avatar ImageView ivAvatar = (ImageView)convertView.findViewById(R.id.imgAvatar); ivAvatar.setImageBitmap(entry.getAvatar());

// set name TextView tvName = (TextView)convertView.findViewById(R.id.tvName); tvName.setText(entry.getName()); // set phone TextView tvPhone = (TextView)convertView.findViewById(R.id.tvPhone); tvPhone.setText(entry.getPhone()); // set email TextView tvEmail = (TextView)convertView.findViewById(R.id.tvEmail); tvEmail.setText(entry.getEmail()); return convertView; } } B5: M file mainActivity.java v sa: Code: package trungh0.study; import import import import import import java.util.ArrayList; java.util.List; android.app.Activity; android.graphics.BitmapFactory; android.os.Bundle; android.widget.ListView;

public class mainActivity extends Activity { private ListView lvPhone; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lvPhone = (ListView)findViewById(R.id.listPhone); List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();

listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(), R.drawable.kimnana),"Kim Nana", "0947-896-668", "Umbala_Kimnana@gmail.com")); listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(), R.drawable.ellytran),"Elly Tran", "0986-686-868", "EllyTran@gmail.com")); listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(), R.drawable.thanhthuy),"Thanh Thuy", "0902-001-002", "ThanhThuy@gmail.com")); listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(), R.drawable.thuhuong),"Thu Huong", "0986-999-999", "ThuHuong9x@gmail.com")); listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(), R.drawable.thuylinh),"Thuy Linh", "0986-006-228", "hot_girl9x@gmail.com")); listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(), R.drawable.trang),"Thuy Trang", "0986-677-028", "bagiabanmaybay@gmail.com")); PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook); lvPhone.setAdapter(adapter); } } Ch : Cc file R.drawable.thanhthuy,R .drawable.thuhuong... l cc file nh c mnh thm vo trong th mc: res\drawable-mdpi B6: Kt qu:

Cn y 4 em v danh

Lp trnh vi cc thnh phn giao din c bn Trong bi ny mnh s gii thiu vi cc bn cch lp trnh vi cc thnh phn giao din c bn nh TextView, EditText v Button V d ca chng ta: C mt EditText cho chng ta nhp Text vo, c mt Button l X l th s hin th dng Text ta nhp vo ln mt TextView B1: Khi to project: ci ny ty do cc bn t, hng dn trong bi HelloWorld B2: Xy dng giao din: m file res/layout/main.xml v lm nh sau: Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"

> <EditText android:id="@+id/editText" android:hint="Nhp Text vo y" // on ny s hin dng ch Nhp Text vo y dng ch m. android:layout_width="fill_parent" android:layout_height="60dp" /> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="60dp" android:text="Text nhp: " /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="X l" /> </LinearLayout> -Ch : androi:hint=" " dng hin th chui m trong Edit Text. Bc 3: X l bt s kin, m file mainActivity.java v lm nh sau: Code: package HelloAndroid.Example; import import import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.widget.Button; android.widget.EditText; android.widget.TextView; android.view.View.OnClickListener;

public class mainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Khai bo cc bin dng

final TextView tv=(TextView)findViewById(R.id.textView); final EditText ed=(EditText)findViewById(R.id.editText); Button bt=(Button)findViewById(R.id.button); //Thit lp s kin button click View.OnClickListener btOnClickListener=new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub tv.setText(ed.getText().toString()); // Set text nhn c ti EditText cho TextView } }; //Set s kin cho Button bt.setOnClickListener(btOnClickListener); } } B4: Save, Ctrl+ F11 v xem kt qu:

Lp trnh Android c bn: x l layout


Thit lp xong mi trng lp trnh Android, ta c th tin hnh x l layout ca Android. Tt nhin, vic thit k layout khng phi l mc ch trong bi ny. Ti ch hng dn cch x l cc i tng v cng n gin trn layout m thi. Ta to mt project Layout mi vi cc thnh phn nh sau:

Cc file quan trng nht trong project ny l cc file sau: 1. string.xml: file thit lp cc tn i tng t trong layout. Khi bin dch, trnh bin dch s tm n file ny c tn bin v so snh vi cc i tng c trong layout to ra file R.class. R.class s c sinh ra to ra mi lin h gia bin v i tng ng nht 2. main.xml: dng thit k giao din cho app. 3. LayoutActivity.java: file code ca chng trnh. u tin, ta tin hnh thm cc bin trong string.xml nh sau: Ta thm 2 bin kiu string l init_msgbtn_label. Hai bin ny s c nh ngha trong code ca string.xml nh sau: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Gioi thieu ve Layout tren Android</string> <string name="init_msg">Xin hay nhap ho va ten</string> <string name="btn_label">Click</string> <string name="app_name">Layout</string> </resources> Tip n, ta sa giao din trong main.xml bng cch thm mi EditTextButton. Vic ny c th thc hin bng cch drag&drop hoc thc hin trc tip trn code nh sau: Ta cn thm cc i tng c tnh cht sau: TextViewl i tng c sn id@+id/text text@string/init_msg EditText id@+id/edit

Button id@+id/button text@string/btn_label

Ch : Ta cn n cc tn i tng c nh ngh sn l text, init_msg,, edit, button, btn_label s c dng code trong chng trnh.

Code trong main.xml s nh sau: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/init_msg" /> <EditText android:id="@+id/edit" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="100px" android:layout_height="wrap_content" android:text="@string/btn_label" /> </LinearLayout> Bc cui cng l ta sa code cho LayoutActivity.java. Ngoi vic to 3 i tng thm vo, ta cn phi ch n vic to event click. package com.layout; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.view.View.*; import android.widget.*; public class LayoutActivity extends Activity { private Button button; private EditText edit; private TextView text;

@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); button = (Button)this.findViewById(R.id.button); edit = (EditText)this.findViewById(R.id.edit); text = (TextView)this.findViewById(R.id.text); button.setOnClickListener(new MyClickAdapter()); } class MyClickAdapter implements OnClickListener { @Override public void onClick(View v) { Editable s = edit.getText(); text.setText("Xin cho Mr/Mrs. " + s); edit.setText(""); } } } OK. Nu bn lm ng cc bc trn, chc chn s chy. Kt qu ca ti nh sau:

Xong. Vy l ta bit cch x l button, text v label trn Android. Chc cc bn thnh cng.

Download ton b code ti y .


ThanhTM
Lp trnh Android c bn: x l Tab

Trong Android, tab c s dng rng ri v l thnh phn khng th thiu trong x l hin th. Trong bi ny, ti s tm hiu cch lp trnh tab v cch chnh sa tab trn Android. Ti s trnh by theo cc mc sau:

1. 2. 3. 4. 5.

Nguyn tc to tab Tap trn top screen Tap bottom screen Tap left screen Tab right screen

Nguyn tc to tab Khi to tab trong Android, ta cn phi tun theo mt nguyn tc to layout cho tab. V d, to tab trn top mn hnh, ta s to layout nh sau:
<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:background="#0094FF" android:layout_width="fill_parent" android:layout_height="fill_parent">

<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

<!-- Tab --> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" />

<!-- Seperator --> <FrameLayout android:background="#222222"

android:layout_width="fill_parent" android:layout_height="1dp" />

<!-- Noi dung tab --> <FrameLayout android:id="@android:id/tabcontent" android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> </TabHost>

to tab, ta phi nh ngha layout l tab bng tag TabHost. Trong id phn ny ta phi ch nh l android:id/tabhost. Sau , trong TabHost, ta nh ngha LinearLayout ritrong nh ngha tag TabWidget, id l @android:id/tabs, ni dung ca tab t trong FrameLayout c id l @android:id/tabcontent. Nu nh ngha layout theo nguyn tc trn th ta c th to tab v hin th tab theo mun. Tip theo, ta cn to cc lp TabActivity thc hin chc nng ca tab. Tap trn top screen th nghim, ta s lp trnh n gin tab trn top mn hnh ca Android. nh ngha main.xml layout:
<?xml version="1.0" encoding="utf-8"?> <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="match_parent" android:orientation="vertical"> <TabWidget android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/tabs">

</TabWidget> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@android:id/tabcontent"> </FrameLayout> </LinearLayout> </TabHost>

Trong Main Activity ta code nh sau: import import import import android.app.TabActivity; android.content.Intent; android.os.Bundle; android.widget.TabHost;

public class TabBarActivityextends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; intent = new Intent().setClass(this, FirstActivity.class); spec = tabHost.newTabSpec("First").setIndicator("First") .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, SecondActivity.class); spec = tabHost.newTabSpec("Second").setIndicator("Second") .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, ThirdActivity.class); spec = tabHost.newTabSpec("Third").setIndicator("Third") .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, FourthActivity.class); spec = tabHost.newTabSpec("Fourth").setIndicator("Fourth") .setContent(intent); tabHost.addTab(spec);

} } To layout tabbar hin th chng lin tip tab_test.xml


<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/txtDisplayedTab" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textAppearance="?android:attr/textAppearanceLarge" android:text="TextView" android:gravity="center|center_vertical"> </TextView> </RelativeLayout>

nh ngha Activity cho tng tab nh sau: FirstActivity.java import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class FirstActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.tab_test); TextView txtView = (TextView) findViewById(R.id.txtDisplayedTab); txtView.setText("First Tab is Selected"); } } Cc Activity ny s c gi trc tip trong main Activity. Tip tc to cc Activity cho tab2, tabe, tab4 nh trn theo cc Activity: SecondActivity.java, ThirdActivity.java, FourthActivity.java. Trong AndroidManifest.xml, ta t cc tab ny trong application gi khi click tab.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.technotalkative.tabbarexample" android:versionCode="1"

android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".TabBarActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="FirstActivity"> </activity> <activity android:name="SecondActivity"> </activity> <activity android:name="ThirdActivity"> </activity> <activity android:name="FourthActivity"> </activity> </application> </manifest>

Kt qu chy nh sau:

Download ton b code tai day

To menu trong android Cho cc bn. Hm nay, chng ta s cng tm hiu v lm 1 demo nh v menu trong android. Menu l g hn cc bn cng bit ri, menu gip user c th d dng truy cp n cc chc nng khc ca ng dng hn. Trong cc ng dng th menu l 1 phn khng th thiu. V d v mt menu:

By gi chng ta s lm 1 demo nh v menu: B1, To 1 project vi tn m bn thch y v d mnh to project l DemoMenu. B2, Trong phn res bn to 1 folder vi tn l menu ( chut phi res -> New -> Folder ) B3, Trong th mc menu bn to 1 file android xml vi tn bt k v d l menu.xml ( chut phi vo folder menu -> New -> Other -> Android -> Android XML file ) B4, Bn vit code vo trong file menu.xml y chnh l phn giao din ca menu s hin ra. Mi thnh phn trong menu c coi l 1 item. Mi item th s c 2 thnh phn chnh l icon,title tt nhin l c th c 1 trong 2 hoc khng c g c Bn vit code xml cho file menu nh sau

PHP Code: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_icon" android:icon="@drawable/icon" /> <item android:id="@+id/menu_text" android:title="android4vn.com" /> <item android:id="@+id/menu_text_and_icon" android:icon="@drawable/icon" android:title="android4vn.com" /> <item android:id="@+id/menu_none" /> </menu> B5, Bn vo file activity y l DemoActivity v override 2 phng thc l onCreateOptionsMenu v onOptionsItemSelected - phng thc onCreateOptionsMenu : c gi khi menu c to ra - phng thc onOptionsItemSelected : c gi khi user chn 1 item trong menu Ch : tin v trnh sai st th khi vit cc phng thc override th bn vo Source -> Override / Implement methods.. ri chn cc phng thc cn override y l onCreateOptionsMenu v onOptionsItemSelected PHP Code: package android.demomenu; import import import import import import android.app.Activity; android.os.Bundle; android.view.Menu; android.view.MenuInflater; android.view.MenuItem; android.widget.Toast;

public class DemoMenuActivity extends Activity { @Override

public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.menu_icon: Toast.makeText(this, "Bn chn item ch c icon :D", Toast.LENGTH_LONG).show(); break; case R.id.menu_text: Toast.makeText(this, "Bn chn item ch c text :)", Toast.LENGTH_LONG).show(); break; case R.id.menu_text_and_icon: Toast.makeText(this, "Bn chn item c text v icon :X", Toast.LENGTH_LONG).show(); break; case R.id.menu_none: Toast.makeText(this, "Bn chn item khng c g c : (", Toast.LENGTH_LONG).show(); break; default: break; } return true; }

@Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; }

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

By gi bn hy chy chng trnh ( Ctrl + F11 ) n vo phm menu trn bn phm ca emu to menu Mt vi hnh nh demo.

Source code download AutoCompleteTextView trong Android AutoCompleteTextView trong Android gn ging nh 1 EditText cho user c th nhp thng tin vo . Tuy nhin, AutoComplete c kh nng a ra cc suggestion ( gi ) user c th chn la m bo cho vic nhp d liu chnh xc. Di y, chng ta s th lm 1 demo nh. B1, To 1 project gi s vi tn l : DemoAutoCompleteTextView ( Vo File->New->Project->Android->Android Project g tn project v tn package ch l tn package phi c dng aaa.bbb ) B2, Vo layout main to AutoCompleteTextView ( vo res->layout>main.xml pha di file chn main.xml g to giao din bng tay)

To 1 AutoCompleteTextView nh sau: file: main.xml PHP Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/ android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <AutoCompleteTextView android:id="@+id/ac_demo" android:layout_width="200dp" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_ok" android:layout_width="100dp" android:layout_height="wrap_content" android:text="OK" /> <TextView android:id="@+id/tv_output" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> android:id y l nh danh cho AutoComplete sau ny mnh c th gi ra c ng n. B3, M file activity ra vit code x l u tin chng ta cn to ra 1 mng cc t AutoCompleteTextView c th da vo m a ra sugggestion. PHP Code: private static final String[] COUNTRIES = { "Belgium", "France", "Italy", "Germany", "Spain", "Viet Nam", "China", "Japan", "Korean", "Russian", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Ar gentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaija n", "Zimbabwe" }; Sau chng ta s to ra 1 ArrayAdapter v set adapter ny cho AutoCompleteTextView file: DemoAutoCompleteTextViewActivity

PHP Code: package demo.autocomplete; import import import import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.ArrayAdapter; android.widget.AutoCompleteTextView; android.widget.Button; android.widget.TextView;

public class DemoAutoCompleteTextViewActivity extends Activity i mplements OnClickListener{ private static final String[] COUNTRIES = { "Belgium", "France", "Italy", "Germany", "Spain", "V iet Nam", "China", "Japan", "Korean", "Russian", "Canada", "Afg hanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Argentina", "Armenia", "Aruba", "Austra lia", "Austria", "Azerbaijan", "Zimbabwe" }; private Button btn_ok; private TextView tv_output; private AutoCompleteTextView ac_txt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_dropdown_item_1line, COUNTRIES); ac_txt = (AutoCompleteTextView) findViewById(R.id.ac_demo ); ac_txt.setThreshold(1); ac_txt.setDropDownHeight(200); ac_txt.setAdapter(adapter); btn_ok = (Button) findViewById(R.id.btn_ok); btn_ok.setOnClickListener(this); tv_output = (TextView) findViewById(R.id.tv_output);

} @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.getId() == R.id.btn_ok) { tv_output.setText(ac_txt.getText().toString()); } } } trong on code ny c x l thm s kin user nhn vo nt ok. Khi chng ta s ly ra on text trong AutoCompleteTextView v set n vo TextView : PHP Code: tv_output.setText(ac_txt.getText().toString()); Cu lnh PHP Code: ac_txt.setThreshold(1); c ngha l khi user g vo 1 k t th bt u a ra suggestion, bn c th set n nhiu hn. Cu lnh PHP Code: ac_txt.setDropDownHeight(200); l set chiu cao ca gi s ra. AutoCompleteTextView tm kim rt tt v d y c t kha l "Viet Nam" th ch cn user g vo Nam th cng s a ra gi l Viet Nam, nhng nu m g vo "iet" th s khng c gi l "Viet Nam" n y bn c th bt u chy project c ri:

Source code: http://www.mediafire.com/?2v4ea0yr0aew9

You might also like