상세 컨텐츠

본문 제목

안드로이드 개발 메트로 UI 메인화면 처럼 만들기 관련

스마트기기개발관련/안드로이드 개발

by AlrepondTech 2016. 5. 23. 11:59

본문

반응형
728x170

 

 

=================================

=================================

=================================

 

 

 

출처: http://blog.csdn.net/wangjinyu501/article/details/9055655

 

 

 今天继续说一下安卓的菜单,之前介绍了:。相信大家对于Metro风格并不陌生,下面就在安卓平台上实现一下这个效果,如图:

                          

                     

  

 

            实现思路:

                               利用动画来实现移动的效果,使用的是TranslateAnimation这个方法。先看一下布局文件:

   activity_main.xml

 

[java] view plain copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:background="#000000"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <!-- 第一层 -->  
  9.   
  10.     <LinearLayout  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="fill_parent"  
  13.         android:layout_weight="1"  
  14.         android:orientation="horizontal" >  
  15.   
  16.         <!-- 第一层 横向 -->  
  17.   
  18.   
  19.         <!-- 第一层 横向左 -->  
  20.   
  21.         <LinearLayout  
  22.             android:layout_width="fill_parent"  
  23.             android:layout_height="fill_parent"  
  24.             android:layout_weight="1"  
  25.             android:orientation="vertical" >  
  26.   
  27.             <LinearLayout  
  28.                 android:layout_width="fill_parent"  
  29.                 android:layout_height="fill_parent"  
  30.                 android:layout_weight="1"  
  31.                 android:orientation="horizontal" >  
  32.   
  33.                 <!-- 1 -->  
  34.   
  35.                 <RelativeLayout  
  36.                     android:id="@+id/nine_one"  
  37.                     android:layout_width="fill_parent"  
  38.                     android:layout_height="fill_parent"  
  39.                     android:layout_weight="1"  
  40.                     android:background="#FFFF00" >  
  41.                 </RelativeLayout>  
  42.                 <!-- 2 -->  
  43.   
  44.                 <RelativeLayout  
  45.                     android:id="@+id/nine_two"  
  46.                     android:layout_width="fill_parent"  
  47.                     android:layout_height="fill_parent"  
  48.                     android:layout_weight="1"  
  49.                     android:background="#FFC0CB" >  
  50.                 </RelativeLayout>  
  51.             </LinearLayout>  
  52.             <!-- 4 -->  
  53.   
  54.             <RelativeLayout  
  55.                 android:id="@+id/nine_four"  
  56.                 android:layout_width="fill_parent"  
  57.                 android:layout_height="fill_parent"  
  58.                 android:layout_weight="1"  
  59.                 android:background="#EE30A7" >  
  60.             </RelativeLayout>  
  61.             <!-- 5 -->  
  62.   
  63.             <RelativeLayout  
  64.                 android:id="@+id/nine_five"  
  65.                 android:layout_width="fill_parent"  
  66.                 android:layout_height="fill_parent"  
  67.                 android:layout_weight="1"  
  68.                 android:background="#EE4000" >  
  69.             </RelativeLayout>  
  70.         </LinearLayout>  
  71.         <!-- 第一层 横向右 -->  
  72.   
  73.         <LinearLayout  
  74.             android:layout_width="fill_parent"  
  75.             android:layout_height="fill_parent"  
  76.             android:layout_weight="2"  
  77.             android:orientation="vertical" >  
  78.   
  79.             <!-- 3 -->  
  80.   
  81.             <RelativeLayout  
  82.                 android:id="@+id/nine_three"  
  83.                 android:layout_width="fill_parent"  
  84.                 android:layout_height="fill_parent"  
  85.                 android:layout_weight="2"  
  86.                 android:background="#FF8C69" >  
  87.             </RelativeLayout>  
  88.             <!-- 6 -->  
  89.   
  90.             <RelativeLayout  
  91.                 android:id="@+id/nine_six"  
  92.                 android:layout_width="fill_parent"  
  93.                 android:layout_height="fill_parent"  
  94.                 android:layout_weight="1"  
  95.                 android:background="#8C8C8C" >  
  96.             </RelativeLayout>  
  97.         </LinearLayout>  
  98.     </LinearLayout>  
  99.     <!-- 第二层 -->  
  100.   
  101.     <LinearLayout  
  102.         android:layout_width="fill_parent"  
  103.         android:layout_height="fill_parent"  
  104.         android:layout_weight="3"  
  105.         android:baselineAligned="false"  
  106.         android:orientation="horizontal" >  
  107.   
  108.         <!-- 7 -->  
  109.   
  110.         <RelativeLayout  
  111.             android:id="@+id/nine_seven"  
  112.             android:layout_width="fill_parent"  
  113.             android:layout_height="fill_parent"  
  114.             android:layout_weight="1"  
  115.             android:background="#8B3E2F" >  
  116.         </RelativeLayout>  
  117.         <!-- 8 -->  
  118.         <!-- 9 -->  
  119.   
  120.         <RelativeLayout  
  121.             android:id="@+id/nine_nine"  
  122.             android:layout_width="fill_parent"  
  123.             android:layout_height="fill_parent"  
  124.             android:layout_weight="1"  
  125.             android:background="#A52A2A" >  
  126.         </RelativeLayout>  
  127.     </LinearLayout>  
  128.   
  129. </LinearLayout>  

    它的效果是这样的:

 

 

 

                                                                                                     

           

 

之后在MainActivity里面对每一个Layout进行动画移动就可以实现平移的效果了。

MainActivity.Java

 

[java] view plain copy
 
  1. import android.app.Activity;  
  2. import android.content.Intent;  
  3. import android.os.Bundle;  
  4. import android.util.DisplayMetrics;  
  5. import android.view.LayoutInflater;  
  6. import android.view.Menu;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.view.Window;  
  10. import android.view.animation.TranslateAnimation;  
  11. import android.widget.RelativeLayout;  
  12. import android.widget.Toast;  
  13.   
  14. /** 
  15.  *  
  16.  */  
  17. public class MainActivity extends Activity {  
  18.     private View viewNine;  
  19.     private LayoutInflater inflater;  
  20.     private RelativeLayout nine_one, nine_two, nine_three, nine_four,  
  21.             nine_five, nine_six, nine_seven, nine_nine;  
  22.     private TranslateAnimation myAnimation_Right, myAnimation_Bottom;  
  23.     private TranslateAnimation myAnimation_Left, myAnimation_Top;  
  24.   
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  29.         inflater = LayoutInflater.from(this);  
  30.         viewNine = inflater.inflate(R.layout.activity_main, null);  
  31.   
  32.         nine_one = (RelativeLayout) viewNine.findViewById(R.id.nine_one);  
  33.         nine_two = (RelativeLayout) viewNine.findViewById(R.id.nine_two);  
  34.         nine_three = (RelativeLayout) viewNine.findViewById(R.id.nine_three);  
  35.         nine_four = (RelativeLayout) viewNine.findViewById(R.id.nine_four);  
  36.         nine_five = (RelativeLayout) viewNine.findViewById(R.id.nine_five);  
  37.         nine_six = (RelativeLayout) viewNine.findViewById(R.id.nine_six);  
  38.         nine_seven = (RelativeLayout) viewNine.findViewById(R.id.nine_seven);  
  39.         nine_nine = (RelativeLayout) viewNine.findViewById(R.id.nine_nine);  
  40.         setContentView(viewNine);  
  41.   
  42.         nine_four.setOnClickListener(new OnClickListener() {  
  43.   
  44.             @Override  
  45.             public void onClick(View v) {  
  46.   
  47.                 Intent intent=new Intent(MainActivity.this,OneActivity.class);  
  48.                 startActivity(intent);  
  49.             }  
  50.         });  
  51.         nine_six.setOnClickListener(new OnClickListener() {  
  52.   
  53.             @Override  
  54.             public void onClick(View v) {  
  55.                   
  56.             }  
  57.         });  
  58.         myAnimation();  
  59.         addAnimation();   
  60.     }  
  61.   
  62.     // 启动动画  
  63.     private void addAnimation() {  
  64.   
  65.         nine_one.startAnimation(myAnimation_Right);  
  66.         nine_two.startAnimation(myAnimation_Bottom);  
  67.         nine_three.startAnimation(myAnimation_Left);  
  68.         nine_four.startAnimation(myAnimation_Bottom);  
  69.         nine_five.startAnimation(myAnimation_Left);  
  70.         nine_six.startAnimation(myAnimation_Top);  
  71.         nine_seven.startAnimation(myAnimation_Left);  
  72.         nine_nine.startAnimation(myAnimation_Left);  
  73.   
  74.     }  
  75.   
  76.     // 动画定义  
  77.     private void myAnimation() {  
  78.         DisplayMetrics displayMetrics = new DisplayMetrics();  
  79.         displayMetrics = this.getResources().getDisplayMetrics();  
  80.         // 获得屏幕宽度  
  81.         int screenWidth = displayMetrics.widthPixels;  
  82.         // 获得屏幕高度  
  83.         int screenHeight = displayMetrics.heightPixels;  
  84.           
  85.         myAnimation_Right = new TranslateAnimation(screenWidth, 000);  
  86.         myAnimation_Right.setDuration(1800);  
  87.   
  88.         myAnimation_Bottom = new TranslateAnimation(00, screenHeight, 0);  
  89.         myAnimation_Bottom.setDuration(1500);  
  90.   
  91.         myAnimation_Left = new TranslateAnimation(-screenWidth, 000);  
  92.         myAnimation_Left.setDuration(2000);  
  93.   
  94.         myAnimation_Top = new TranslateAnimation(00, -screenHeight, 0);  
  95.         myAnimation_Top.setDuration(2500);  
  96.     }  
  97.   
  98.     @Override  
  99.     public boolean onCreateOptionsMenu(Menu menu) {  
  100.         // Inflate the menu; this adds items to the action bar if it is present.  
  101.         // getMenuInflater().inflate(R.menu.activity_main, menu);  
  102.         return true;  
  103.     }  
  104.   
  105. }  

         虽然效果还可以,但是布局文件由于使用嵌套,这样毁造成绘制窗口时性能的问题。所以你对程序要求很严格,那么建议使用RelativewLayout来布局,并且减少使用嵌套。

        下载地址

 

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://lsit81.tistory.com/entry/Android-RelativeLayout-%EB%B0%B0%EC%B9%98-%EA%B4%80%EB%A0%A8

 

 

안드로이드로 레이아웃(Layout)을 작성할 때 보통은 LinearLayout을 많이 사용합니다.
제일 간편하니깐요. 

하지만, 단순히 일렬로 나열하는게 아니라 자식들간에 서로 겹치기도 하고, 정렬 또는 배치 등을
조금 규칙적으로 하기 위해서는 FrameLayout이나 RelativeLayout을 이용하기도 합니다.

RelativeLayout에서 부모와 자식간, 그리고 기준과의 배치에 대해서 알아보겠습니다.

 

 

 

 
 

부모와 자식간의 관계는 위의 그림과 같습니다.
예를 들어 부모 안에서 자식 View를 가운데 배치하고 싶으면 다음과 같이 작성하면 됩니다.

 

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

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:keepScreenOn="true" >

 

<ImageView

android:layout_centerInParent="true"

android:layout_width="wrap_content"

android:layout_height="match_parent"/>


</RelativeLayout>

 



그리고 RelativeLayout을 사용할 때 부모안의 다른 자식 뷰를 기준으로 상대적인 위치를 적용할 수도 있습니다.
예를 들어 A라는 뷰가 이미 자리잡고 있다면, 이번에 새로 배치할 B라는 뷰는 'A의 바로 왼쪽, 또는 오른쪽에 배치하라'고

지정할 수 있는거죠. 그 배치 방법은 아래와 같습니다.

 

 

 

 

 

사실 RelativeLayout이 할 수 있는 일들은 FrameLayout 등을 통해서도 똑같이 구현할 수 있지만, 

아무래도 미리 만들어놓은 템플렛 레이아웃을 사용하는 것이 훨씬 더 편리하긴 하죠. ^^;

 

 

 

* 출처 : 

http://snowbora.com/441

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.androidside.com/plugin/mobile/board.php?bo_table=B49&wr_id=135732

 

 

하세요 아래와 같이 메트로 UI를 제작 해보고싶은데 레이아웃을 어떻게 잡아야 할지 몰라 문의드립니다.
 
아래 비씨카드 앱에서 편집 상태가되면 해당 메뉴들을 drag n drop으로 위치 조정을 할수있습니다.
 
이때 drag 이벤트에 따라 해당 메뉴가 움직이고 다른 메뉴와 어느정도 겹쳐지면 기존 메뉴는 위 또는 아래로
 
자동으로 움직이도록 구현 되어있습니다.
 
 
이 영상에 있는 액션이랑 거의 흡사한데 GridView를 사용하면 아래와 같은 레이아웃을 구성할수가 없어서 다른 레이아웃을 
 
사용해야할듯 싶은데 도무지 감이 잡히지 않습니다. ㅠ
 
그리고 또 문제는 API8 부터 지원을 해야해서 Drag n Drop은 구현할 것입니다. 레이아웃 구성은 GridLayout도 생각해 봤으나
 
동적으로 다른 메뉴들이 움직이도록 구현하는게 힘들듯 합니다. 
 
기본적으로 어떤 레이아웃을 써서 만들어야할지 조차 감이 안와서 고수님들께 질문드립니다.
 
감사합니다.. !!
 

 

 

-----------------------------------------------------------------------------------------------------------------------------

그리드 레이아웃으로 그릴수 있겠네요~

 
아니면 리니어레이아웃을 여러번 쪼개는 방법도 있습니다~ㅎㅎ

 

-->

답변감사드립니다. 

위에 써놨는데 그리드레이아웃이나 리니어레이아웃을 사용하면 Drag and Drop시 메뉴들위치를 동적으로 움직이는게 
가능한가요? 간단한 가이드 부탁드립니다.!!
 
------------------------------------------------------------------------------------------------------------------------------------
 
 
http://blog.csdn.net/cupidove/article/details/7640831
레이아웃 예제인데 참고해보세요
 
---->
답변감사드립니다.
올려주신 사이트는 기본레이아웃 샘플코드네요 ^^
단순 화면구성은 쉽게 하겠으나 동적으로 메뉴들이 이동되는부분이 어려워서 문의드린거였습니다.
감사합니다 ㅎ
 
-----------------------------------------------------------------------------------------------------------------------------------------
 
Drag and Drop 시 동영상처럼 작동을 하려면 그리드 레이아웃보다는 리니어 레이아웃으로 그려주는게 좋을거 습니다.~
 
http://blog.csdn.net/moubenmao_jun/article/details/8771863
마지막에 drag and drop
참고해보세요~
---------->
연달아 답변 감사드립니다 ^^
참고 하도록하겠습니다 
Drag n Drop은 2.3대 버전에선 DragEvent를 지원하지않아서 따로 만들었습니다 ^^

 

-------------------------------------------------------------------------------------------------------------------------

 

그냥 릴레티브레리아웃으로 하면 쉽게 할 수 있을 뜻하네요 ㅇ.ㅇ

 

 

 

 

반응형

 

 

728x90

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://stackoverflow.com/questions/18117750/android-metro-style-design-pattern

 

I'm designing a Metro-Style Android application.
Tiles, Groups & Scrolls are done!

For who're not familiar with Metro-Style (aka Modern UI), please take a look at the following picture.

 

Question :
What's the best (performance wise) design pattern for sorting tiles dynamically in 2 rows & multiple columns ?

- HorizontalScrollView - - LinearLayout   - - - Every 2 tiles have same weight

Or

- HorizontalScrollView - - TableLayout - - - Every 2 tiles have same row

Or

- Something else ?

 

---------------------------------------------------------------

 

 

 

Try this layout:
| Relative Layout
|--> HorizontalScrollView
|--|--> LinearLayout (showDivider=middle|beginning|end, and divider drawable=50x1])
|--|--|--> TableLayout (With weight=1)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#011a41" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".Main" > <HorizontalScrollView android:id="@+id/horizontalScrollView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:divider="@drawable/divider" android:showDividers="middle|beginning|end" > <TableLayout android:layout_width="wrap_content" android:layout_height="match_parent" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <ImageView android:id="@+id/imageView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <ImageView android:id="@+id/imageView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </TableRow> </TableLayout> <TableLayout android:layout_width="wrap_content" android:layout_height="match_parent" > <TableRow android:id="@+id/tableRow5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/tableRow6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </TableRow> <TableRow android:id="@+id/tableRow7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CheckBox" /> </TableRow> <TableRow android:id="@+id/tableRow8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" /> </TableRow> </TableLayout> </LinearLayout> </HorizontalScrollView> </RelativeLayout>
shareimprove this answer

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://stackoverflow.com/questions/20732701/relative-layout-bottom-align-issue

 

 

I'm trying to implement a relative layout, similar to below picture. But when trying to bottom align the bottom-right text view, it goes out of the screen.

 

What is the best/minimal way to design below layout?

Code, currently I'm trying:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >      <RelativeLayout         android:id="@+id/dash1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:gravity="top" >          <RelativeLayout             android:id="@+id/view_subdash_top_right"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_alignParentRight="true"             android:layout_toRightOf="@id/tv_name" >              <TextView                 android:id="@+id/tv_instrument_change"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:layout_below="@id/tv_text2"                 android:gravity="right"                 android:text="text1" />              <TextView                 android:id="@+id/tv_text2"                 android:layout_width="match_parent"             android:layout_height="wrap_content"                 android:layout_alignParentTop="true"                 android:gravity="right"                 android:text="text2" />         </RelativeLayout>          <TextView             android:id="@+id/tv_name"             android:layout_width="wrap_content"             android:layout_height="match_parent"             android:layout_alignBottom="@id/view_subdash_top_right"             android:gravity="bottom|center"             android:text="name" />     </RelativeLayout>      <RelativeLayout         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_below="@id/dash1"         android:gravity="top" >          <!-- Here to enter bottom left -->          <TextView             android:id="@+id/tv_bottom_right"             android:layout_width="wrap_content"             android:layout_height="match_parent"             android:layout_alignParentRight="true"             android:gravity="right|bottom"             android:text="bottom right" />     </RelativeLayout>  </RelativeLayout>

 

--------------------------------------------------------------------------------------------------------------

 

// try this <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >      <RelativeLayout         android:id="@+id/rel_top"         android:layout_width="wrap_content"         android:layout_height="wrap_content">         <TextView             android:id="@+id/tv_top_left"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignBottom="@id/rel_top_right"             android:text="Top Left Text" />         <RelativeLayout             android:id="@+id/rel_top_right"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_alignParentRight="true"             android:gravity="right"             android:layout_toRightOf="@id/tv_top_left" >              <TextView                 android:id="@+id/tv_top_text1"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:text="Top Text1" />              <TextView                 android:id="@+id/tv_top_text2"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:layout_below="@id/tv_top_text1"                 android:text="Top Text2" />         </RelativeLayout>     </RelativeLayout>      <RelativeLayout         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_below="@id/rel_top"         android:gravity="top" >         <TextView             android:id="@+id/tv_bottom_right"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignParentRight="true"             android:layout_alignBottom="@id/rel_bottom_left"             android:text="Bottom Right Text" />          <RelativeLayout             android:id="@+id/rel_bottom_left"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_toLeftOf="@id/tv_bottom_right" >              <TextView                 android:id="@+id/tv_bottom_text1"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:text="Bottom Text1" />             <TextView                 android:id="@+id/tv_bottom_text2"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:layout_below="@id/tv_bottom_text1"                 android:text="Bottom Text2" />         </RelativeLayout>     </RelativeLayout> </RelativeLayout>
shareimprove this answer

 

------------------------------------------------------------------------------------------

 

If you want to fill up the whole screen with those views, I'd use weighted LinearLayout

<LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical">      <LinearLayout             android:layout_width="match_parent"             android:layout_height="match_parent"             android:layout_weight="1">              <View                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:layout_weight="4"/>               <View                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:layout_weight="1"/>     </LinearLayout>      <LinearLayout            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_weight="1">               <View                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:layout_weight="1"/>               <View                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:layout_weight="4"/>      </LinearLayout> </LinearLayout>
shareimprove this answer

 

 

 

 

=================================

=================================

=================================

 

 

 

출처: https://mindfiremobile.wordpress.com/2014/04/21/relative-layout-design-in-android-using-xamarin/

 

 

Introduction:
Xamarin provides different layout for designing the user interface in Android.
Some common ones being used are Relative Layout, Linear Layout, Grid Layout, Table Layout, Frame Layout etc. Most of them are understandable from their name itself. Here we will discuss about how to design using Relative Layout in Xamarin for Android.

Description:
As the name suggests, Relative Layout mainly makes use of the controls present in the Designer and places controls relatively to each other. The most important aspect of this design being the First element placed inside the tag. The places itself depending on the properties set for the children in the Relative Layout.
For example:
if the Gravity property of the Element is set to “Center” then the controls inside the Layout would set themselves exactly at the vertical and horizontal center. Most common property that specify the positioning inside a Relative Layout are :

  • layout_below
  • layout_above
  • layout_toLeftOf
  • layout_toRightOf

Demo:
Here’s a code snippet demonstrating the placement of TextViews in Relative Layout.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relativeLayout1"
    android:gravity="center">
    <TextView
        android:text="Top Text with gravity of Relative Layout as Center"
        android:layout_width="match_parent"
        android:layout_height="64.8dp"
        android:id="@+id/textViewTop"
        android:gravity="center"
        android:background="#ffaa758c"
        android:textColor="#000000" />
    <TextView
        android:text="Middle Text view"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="164.3dp"
        android:layout_height="64.3dp"
        android:layout_below="@id/textViewTop"
        android:id="@+id/textViewMiddle"
        android:textColor="#000000"
        android:background="#ffb4e03c"
        android:gravity="center" />
    <TextView
        android:text="Bottom Textview"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="60.1dp"
        android:layout_toRightOf="@id/textViewMiddle"
        android:id="@+id/textView7"
        android:layout_below="@+id/textViewMiddle"
        android:background="#ff60dce5"
        android:textColor="#000000"
        android:gravity="center" />
</RelativeLayout>

Below is a screen shot of the resulted layout.

 

Conclusion:
Relative layout can be easily used to place items one besides the other relatively. In case of extended long layout it is better to make a Scrollview as a parent and include a Relative Layout inside it so as to enable scrolling.

Written ByAnobik Dey, Software Developer, Mindfire Solutions

 

 

 

=================================

=================================

=================================

 

 




출처: https://developer.android.com/guide/topics/ui/declaring-layout.html

 

 

레이아웃은 사용자 인터페이스에 대한 시각적 구조를 정의합니다. 예컨대 액티비티 또는 앱 위젯에 대한 UI가 이에 해당됩니다. 레이아웃을 선언하는 데에는 다음과 같은 두 가지 방법이 있습니다.

  • UI 요소를 XML로 선언. Android가 위젯과 레이아웃 등과 같이 보기 클래스와 하위 클래스에 상응하는 간단한 XML 어휘를 제공합니다.
  • 런타임에 레이아웃 요소를 인스턴트화. 애플리케이션이 프로그래밍 방법으로 보기 및 ViewGroup객체를 만들 수 있습니다(그리고 그 속성을 조작하기도 합니다).

Android 프레임워크에서는 이와 같이 애플리케이션의 UI를 선언하고 관리하기 위한 메서드를 둘 중 하나만, 또는 둘 모두 사용할 수 있는 유연성을 부여합니다. 예를 들어, 애플리케이션의 기본 레이아웃을 XML로 선언하면서 그 안에 나타날 화면 요소와 그 속성을 포함할 수 있습니다. 그러면 이제 애플리케이션에 코드를 추가하여 화면 객체의 상태를 수정하도록 할 수 있으며, 여기에는 런타임에 XML로 선언된 것도 포함됩니다.

UI를 XML로 선언하는 것의 이점은 이렇게 하면 애플리케이션을 그 행동을 제어하는 코드로부터 따로 표시하기가 더 좋다는 것입니다. UI 설명은 애플리케이션 코드의 외부에 있습니다. 이는 다시 말해 소스 코드를 수정하고 다시 컴파일링하지 않아도 이를 수정 또는 변경할 수 있다는 뜻입니다. 예를 들어, 서로 다른 화면 방향, 사로 다른 기기 화면 크기 및 서로 다른 언어에 대해 XML 레이아웃을 생성할 수 있습니다. 이외에도 레이아웃을 XML로 선언하면 UI의 구조를 시각화하기가 더 쉬우므로 문제를 디버깅하기도 더 쉽습니다. 따라서, 이 문서는 레이아웃을 XML로 선언하는 방법을 가르치는 데 주안점을 두고 있습니다. 런타임에 보기 객체를 인스턴트화하는 것에 흥미가 있는 경우, ViewGroup 및 View 클래스 참조를 참조하십시오.

일반적으로 UI 요소를 선언하는 데 쓰이는 XML 어휘는 클래스와 메서드 명명을 충실히 따릅니다. 여기에서 요소 이름은 클래스 이름에 상응하며 속성 이름은 메서드에 상응합니다. 사실 이러한 일치성은 아주 직접적인 경우가 잦아 어느 XML 속성이 클래스 메서드에 상응하는지를 추측할 수 있고, 어느 클래스가 주어진 XML 요소에 상응하는지도 추측할 수 있습니다. 다만 모든 어휘가 다 같지는 않다는 점을 유의하십시오. 몇몇 경우에는 명명에 약간의 차이점이 있습니다. 예를 들어, EditText 요소에는 text 속성이 있으며 이는EditText.setText()에 상응합니다.

팁: 여러 가지 레이아웃 유형에 대해서는 보편적인 레이아웃 객체를 참조하십시오. 여러 가지 레이아웃을 구축하는 데 대한 튜토리얼 모음도 있습니다. Hello 보기 튜토리얼 가이드를 참조하십시오.

XML 쓰기


Android의 XML 어휘를 사용하면 UI 레이아웃과 그 안에 들어있는 화면 요소를 HTML에서 웹 페이지를 디자인할 때와 같은 방식으로 신속하게 디자인할 수 있습니다. 즉 일련의 중첩된 요소를 사용하는 것입니다.

각 레이아웃 파일에는 반드시 딱 하나의 루트 요소만 있어야 하며, 이는 보기 또는 ViewGroup 객체여야 합니다. 루트 요소를 정의했으면, 하위 요소로 더 많은 레이아웃 요소 또는 위젯을 추가하여 점층적으로 레이아웃을 정의할 보기 계층을 구축할 수 있습니다. 예를 들어, 다음은 수직 LinearLayout을 사용하여TextView 및 Button을 보유하는 XML 레이아웃을 나타낸 것입니다.

<?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:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
</LinearLayout>

레이아웃을 XML로 선언하고 나면 그 파일을 Android 프로젝트의 res/layout/ 디렉터리 내에 .xml 확장자로 저장하여 적절하게 컴파일링되도록 합니다.

레이아웃 XML 파일의 구문에 대한 자세한 정보는 레이아웃 리소스 문서에서 확인할 수 있습니다.

XML 리소스 로딩


애플리케이션을 컴파일링하는 경우, 각 XML 레이아웃 파일이 View 리소스 안에 컴파일링됩니다. 애플리케이션 코드로부터 가져온 레이아웃 리소스는Activity.onCreate() 콜백 구현에 로딩해야 합니다. 이렇게 하려면 setContentView()를 호출한 다음, 이를 R.layout.layout_file_name 형태로 레이아웃 리소스의 참조에 전달합니다. 예를 들어, XML 레이아웃이 main_layout.xml로 저장된 경우, 이것을 액티비티에 대해 로딩하려면 다음과 같이 하면 됩니다.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
}

액티비티 내의 onCreate() 콜백 메서드는 액티비티가 시작될 때 Android 프레임워크가 호출합니다(수명 주기에 대한 논의는 액티비티 문서에서 확인하십시오).

속성


모든 보기 및 ViewGroup 객체는 각자 나름대로의 다양한 XML 속성을 지원합니다. 몇몇 속성은 보기 객체에만 특화되어 있지만(예를 들어, TextView는textSize 속성을 지원), 이와 같은 속성은 이 클래스를 확장할 수 있는 모든 보기 객체가 상속하기도 합니다. 모든 보기 객체에 공통으로 쓰이는 것도 몇 가지 있습니다. 왜냐하면 이들은 루트 보기 클래스에서 상속된 것이기 때문입니다(예: id 속성). 그리고 나머지 속성은 "레이아웃 매개변수"로 간주됩니다. 이들은 보기 객체의 특정한 레이아웃 방향을 설명하는 것으로, 이는 해당 객체의 상위 VeiwGroup 객체에서 정의된 바에 따릅니다.

ID

모든 보기 객체에는 연관된 정수 ID가 있을 수 있습니다. 이는 트리 내에서 해당 보기를 고유하게 식별하기 위한 것입니다. 애플리케이션이 컴파일링되면 이 ID가 정수로 참조되지만, ID는 일반적으로 레이아웃 XML 파일에 문자열로 할당되며, id 속성으로 쓰입니다. 이것은 모든 보기 객체에 공통적인 XML 속성으로 (View 클래스가 정의) 이것을 매우 자주 사용하게 됩니다. ID에 대한, XML 태그 내에 있는 구문은 다음과 같습니다.

android:id="@+id/my_button"

문자열 시작 부분에 있는 앳 기호(@)는 XML 파서가 ID 문자열의 나머지를 구문 분석하고 확장하여 ID 리소스로 식별해야 한다는 것을 나타냅니다. 더하기 기호(+)는 이것이 새 리소스 이름이며, 이것을 반드시 생성하여 우리 리소스에 추가해야 한다는 것을 뜻합니다(R.java 파일에서). Android 프레임워크는 다른 ID 리소스도 아주 많이 제공합니다. Android 리소스 ID를 참조할 때에는 더하기 기호는 필요하지 않지만 android 패키지 네임스페이스를 다음과 같이 반드시 추가해야 합니다.

android:id="@android:id/empty"

android 패키지 네임스페이스를 제자리에 넣으면 이제 ID를 로컬 리소스 클래스에서가 아니라 android.R 리소스 클래스에서 참조하고 있는 것이 됩니다.

보기를 생성하고 이를 애플리케이션에서 참조하는 데 쓰이는 보편적인 패턴은 다음과 같습니다.

  1. 레이아웃 파일에서 보기/위젯을 정의한 다음 이를 고유한 ID에 할당합니다.
    <Button android:id="@+id/my_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/my_button_text"/>
  2. 그런 다음 보기 객체의 인스턴스를 생성하고 이를 레이아웃에서 캡처합니다 (일반적으로 onCreate() 메서드에서).
    Button myButton = (Button) findViewById(R.id.my_button);

RelativeLayout을 생성할 때에는 보기 객체의 ID를 정의하는 것이 중요합니다. 관계 레이아웃에서는 형제 보기가 또 다른 형제 보기와 관련된 자신의 레이아웃을 정의할 수 있으며, 이를 고유한 ID로 참조하게 됩니다.

ID는 트리 전체를 통틀어 고유할 필요는 없지만, 트리에서 검색하고 있는 부분 내에서는 고유해야 합니다(이것이 트리 전체인 경우가 잦으므로, 가급적이면 완전히 고유한 것을 쓰는 것이 가장 좋습니다).

레이아웃 매개변수

layout_something이라는 XML 레이아웃 속성이 보기가 상주하는 ViewGroup에 대해 적절한 보기의 레이아웃 매개변수를 정의합니다.

모든 ViewGroup 클래스가 중첩된 클래스를 하나씩 구현하며 이것이 ViewGroup.LayoutParams를 확장합니다. 이 하위 클래스에는 각 하위 보기의 크기와 위치를 보기 그룹에 적절한 방식으로 정의하는 속성 유형이 들어 있습니다. 그림 1에서 볼 수 있듯이, 상위 보기 그룹이 각 하위 보기의 레이아웃 매개변수를 정의합니다(하위 보기 그룹 포함).

 

그림 1. 각 보기와 연관된 레이아웃 매개변수가 있는 보기 계층을 시각화한 것입니다.

모든 LayoutParams 하위 클래스에는 설정 값에 대한 각기 자신만의 구문이 있다는 점을 눈여겨 보십시오. 각 하위 요소는 자신의 상위에 적합한 LayoutParams를 정의해야 합니다. 다만 이것은 자신의 하위에 대해 각기 다른 LayoutParams도 정의할 수 있습니다.

모든 보기 그룹에는 너비와 높이가 포함되며(layout_width 및 layout_height), 각 보기는 이들을 반드시 정의해야 합니다. 선택 사항으로 여백과 테두리도 포함하는 LayoutParams도 많습니다.

 

너비와 높이는 정확한 치수로 지정할 수 있습니다. 다만 이것은 자주 하지 않는 것이 좋습니다. 그보다는 다음과 같은 상수 중 하나를 사용하여 너비 또는 높이를 설정하는 경우가 더 많습니다.

  • wrap_content 보기에 콘텐츠에 필요한 치수대로 알아서 크기를 조정하라고 합니다.
  • match_parent (다른 이름은 fill_parent 로, API 레벨 8 이전에 해당) 보기에 상위 보기 그룹이 허용하는 한 최대한으로 커지라고 합니다.

일반적으로 픽셀과 같이 절대적인 단위를 사용하여 레이아웃 너비와 높이를 지정하는 것은 권장하지 않습니다. 그 대신, 밀도 독립적인 픽셀 단위와 같이 상대적인 측정치를 사용하는 것(

dp

), 

wrap_content

, 또는 

match_parent

등이 더 낫습니다. 이렇게 하면 애플리케이션이 다양한 기기 화면 크기에 걸쳐서도 적절하게 표시되도록 보장하는 데 도움이 되기 때문입니다. 허용된 측정 유형은 사용 가능한 리소스에 정의되어 있습니다.

레이아웃 위치


보기의 모양은 직사각형입니다. 보기에는 위치가 있으며, 이는 한 쌍의 왼쪽 및 상단 좌표, 그리고 두 개의 치수가 너비와 높이를 나타내는 형식으로 표현됩니다. 위치와 치수의 단위는 픽셀입니다.

보기의 위치를 검색할 수 있습니다. getLeft() 및 getTop() 메서드를 호출하면 됩니다. 전자는 보기를 나타내는 직사각형의 왼쪽, 즉 X 좌표를 반환합니다. 후자는 보기를 나타내는 직사각형의 상단, 즉 Y 좌표를 반환합니다. 이들 메서드는 둘 다 보기의 위치를 해당 보기의 상위와 관련지어 반환합니다. 예를 들어, getLeft()가 20을 반환하는 경우 이는 해당 보기가 그 보기의 바로 상위의 왼쪽 가장자리에서 오른쪽으로 20픽셀 떨어진 곳에 있다는 뜻입니다.

이외에도 불필요한 계산을 피하기 위해 여러 가지 편의 메서드가 제공됩니다. 구체적으로 getRight() 및 getBottom()을 들 수 있습니다. 이들 메서드는 해당 보기를 나타내는 직사각형의 오른쪽과 하단 가장자리의 좌표를 반환합니다. 예를 들어 getRight()를 호출하는 것은 다음 계산과 비슷합니다.getLeft() + getWidth()

크기, 안쪽 여백 및 여백


보기의 크기는 너비와 높이로 표현됩니다. 사실 하나의 보기는 두 쌍의 너비 및 높이 값을 소유합니다.

첫 번째 쌍을 측정된 너비 및 측정된 높이라고 합니다. 이들 치수는 보기가 상위 내에서 얼마나 커지고자 하는지를 정의합니다. 측정된 치수를 가져오려면getMeasuredWidth() 및 getMeasuredHeight()를 호출하면 됩니다.

두 번째 쌍은 단순히 너비 및 높이라고 일컬으며, 때로는 그리기 너비 및 그리기 높이로 부를 때도 있습니다. 이러한 치수는 그리기 시간 및 레이아웃 후에 보기가 화면에 표시되는 실제 크기를 정의합니다. 이들 값은 측정된 너비 및 높이와 달라도 되지만 꼭 달라야 하는 것은 아닙니다. 너비와 높이를 가져오려면 getWidth() 및 getHeight()를 호출하면 됩니다.

보기의 치수를 측정하려면 보기는 자신의 안쪽 여백을 감안합니다. 안쪽 여백은 보기의 왼쪽, 상단, 오른쪽 및 하단 부분에 대해 픽셀로 표시됩니다. 안쪽 여백은 정해진 픽셀 수를 사용하여 보기의 콘텐츠를 오프셋하는 데 쓰일 수도 있습니다. 예를 들어 왼쪽 안쪽 여백을 2로 설정하면 해당 보기의 콘텐츠를 왼쪽 가장자리에서 오른쪽으로 2픽셀 밀어냅니다. 안쪽 여백을 설정할 때에는 setPadding(int, int, int, int) 메서드를 사용하면 되고, 이를 쿼리하려면getPaddingLeft()getPaddingTop()getPaddingRight() 및 getPaddingBottom()을 사용하면 됩니다.

보기가 안쪽 여백을 정의할 수는 있지만, 여백에 대한 지원은 전혀 제공하지 않습니다. 다만 보기 그룹이 그와 같은 지원을 제공합니다. 자세한 정보는ViewGroup 및 ViewGroup.MarginLayoutParams를 참조하십시오.

치수에 대한 자세한 정보는 치수 값을 참조하십시오.

보편적인 레이아웃


ViewGroup 클래스의 각 하위 클래스는 각기 고유한 방식으로 자신 안에 중첩한 보기를 표시합니다. 아래는 Android 플랫폼에서 기본 제공되는, 보다 보편적인 레이아웃 유형을 몇 가지 나타낸 것입니다.

참고: 하나 이상의 레이아웃을 또 다른 레이아웃에 중첩하여 UI 디자인을 이룰 수도 있지만, 레이아웃 계층을 가능한 한 얕게 유지하도록 애써야 합니다. 중첩된 레이아웃이 적을수록 레이아웃이 더욱 빠르게 그려집니다(가로로 넓은 보기 계층이 깊은 보기 계층보다 낫습니다).

선형 레이아웃

여러 하위를 하나의 가로 방향 또는 세로 방향 행으로 정리하는 레이아웃. 이것은 창의 길이가 화면 길이를 웃도는 경우 스크롤 막대를 만듭니다

.

관계 레이아웃

여러 하위 객체의 위치를 서로 관련지어 나타내거나(하위 A가 하위 B의 왼쪽), 상위와 관련지어 나타낼 수 있도록 해줍니다(상위의 맨 위에 맞춰 정렬)

.

웹 보기

웹 페이지를 표시합니다

.

어댑터로 레이아웃 구축하기


레이아웃의 콘텐츠가 동적이거나 미리 정의되지 않은 경우, AdapterView의 하위 클래스가 되는 레이아웃을 사용하여 런타임에 보기로 레이아웃을 채울 수 있습니다. AdapterView 클래스의 하위 클래스는 Adapter를 사용하여 자신의 레이아웃에 데이터를 바인딩합니다. Adapter가 데이터 소스와 AdapterView레이아웃 사이의 중개자 역할을 합니다. —Adapter가 데이터를 검색하여(배열 또는 데이터베이스 쿼리와 같은 소스로부터) 각 항목을 보기로 변환해서AdapterView 레이아웃에 추가될 수 있도록 합니다.

어댑터로 지원되는 보편적인 레이아웃의 몇 가지 예는 다음과 같습니다.

목록 보기

스크롤로 내리는 하나의 열 목록을 표시합니다

.

눈금 보기

스크롤로 내리는 열과 행의 눈금을 표시합니다

.

데이터로 어댑터 보기 채우기

ListView 또는 GridView와 같은 AdapterView를 채우려면 AdapterView 인스턴스를 Adapter에 바인딩하면 됩니다. 이는 외부 소스로부터 데이터를 검색하여 각 데이터 항목을 나타내는 View를 생성합니다.

Android는 Adapter의 하위 클래스를 여러 개 제공합니다. 이는 여러 가지 종류의 데이터를 검색하고 AdapterView에 대한 보기를 구축하는 데 유용합니다. 가장 보편적인 어댑터 두 가지를 예로 들면 다음과 같습니다.

ArrayAdapter
이 어댑터는 데이터 소스가 배열일 때 사용하십시오. 기본적으로 ArrayAdapter가 각 항목에서 toString()를 호출하고 그 콘텐츠를 TextView에 배치함으로써 각 배열 항목에 대한 보기를 생성합니다.

예를 들어, ListView로 문자열 배열을 표시하고자 하는 경우, 생성자를 사용하여 새로운 ArrayAdapter를 초기화해서 각 문자열과 문자열 배열에 대한 레이아웃을 지정하면 됩니다.

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

이 생성자에 대한 인수는 다음과 같습니다.

  • 개발자의 앱 Context
  • 배열에 있는 각 문자열에 대한 TextView가 들어있는 레이아웃
  • 문자열 배열

그런 다음 ListView에서 setAdapter()를 호출하기만 하면 됩니다.

ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);

각 항목의 외관을 사용자 지정하려면 배열의 객체에 대한 toString() 메서드를 재정의하면 됩니다. 아니면, 각 항목에 대하여 TextView가 아닌 다른 보기를 생성하고자 하는 경우(예를 들어 각 배열 항목에 ImageView를 원하는 경우), ArrayAdapter 클래스를 확장하고 getView()를 재정의하여 각 항목에 대해 원하는 유형의 보기를 반환하도록 할 수 있습니다.

SimpleCursorAdapter
이 어댑터는 데이터 출처가 Cursor일 때 사용하십시오. SimpleCursorAdapter를 사용하는 경우, Cursor에 있는 각 행에 대하여 사용할 레이아웃을 지정해야 합니다. 또한 Cursor 의 어느 열이 레이아웃의 어느 보기에 삽입되어야 할지도 지정해야 합니다. 예를 들어 사람 이름과 전화번호로 이루어진 목록을 생성하고자 하는 경우, 각 사람에 대해 행이 하나씩 있고 이름과 번호에 대해 열이 들어있는 Cursor를 반환하는 쿼리를 수행하면 됩니다. 그런 다음 레이아웃에서 각 결과에 대하여 Cursor의 어느 열을 원하는지 지정하는 문자열 배열을 만들 수 있고, 각 열이 배치되어야 하는 상응하는 보기를 지정하는 정수 배열을 만들면 됩니다.

 

String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};

SimpleCursorAdapter를 인스턴트화하는 경우, 각 결과에 대해 사용할 레이아웃과 결과가 들어있는 Cursor, 그리고 다음의 두 배열을 전달합니다.

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);

그러면 SimpleCursorAdapter가 Cursor에 있는 각 행에 대한 보기를 하나씩 생성합니다. 이때 상응하는 toViews 보기 안에 각 fromColumns 항목을 삽입함으로써 제공된 레이아웃을 사용합니다.

.

애플리케이션의 수명이 진행되는 동안에 어댑터가 읽는 기본 데이터를 변경하는 경우, notifyDataSetChanged()를 호출해야 합니다. 이렇게 하면 첨부된 보기에 데이터가 변경되었으며 스스로 새로 고쳐야 한다는 사실을 알려줍니다.

클릭 이벤트 처리

AdapterView에 있는 각 항목에서의 클릭 이벤트에 응답하려면 AdapterView.OnItemClickListener 인터페이스를 구현하면 됩니다. 예:

// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // Do something in response to the click
    }
};

listView.setOnItemClickListener(mMessageClickedHandler);

 

 

=================================

=================================

=================================

 

 

반응형
그리드형


관련글 더보기

댓글 영역