'전체 글'에 해당되는 글 107건

  1. 2011.03.21 13-4 대화상자
  2. 2011.03.21 [13-3] 메뉴
  3. 2011.03.21 [13-2-D2][UI 설계] ListView, Adapter

2011. 3. 21. 13:33 android App

13-4 대화상자


13-4 대화상자

[01] 대화 상자

1. 단순한 대화 상자
<?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="아래 버튼을 눌러 대화상자를 호출하시오."
    />
<Button
    android:id="@+id/call" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="대화상자 호출"
    />
</LinearLayout>

 

 

package exam.dialog;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class DialogTest extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_dialogtest);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    //* 빌더 생성 후 속성 설정
    AlertDialog.Builder bld = new AlertDialog.Builder(DialogTest.this);
    bld.setTitle("알립니다.");
    bld.setMessage("대화상자를 열었습니다.");
    bld.setIcon(R.drawable.icon);
    bld.show();
    //*/

    /* 연쇄적인 호출
    new AlertDialog.Builder(DialogTest.this)
    .setTitle("알립니다.")
    .setMessage("대화상자를 열었습니다.")
    .setIcon(R.drawable.icon)
    .show();
    //*/
   }
  });  
 }
}

 


2. 대화상자의 버튼 생성

package exam.dialog;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class DialogButton extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_dialogtest);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    /* 빈 리스너 작성
       new AlertDialog.Builder(DialogButton.this)
       .setTitle("알립니다.")
       .setMessage("대화상자를 열었습니다.")
       .setIcon(R.drawable.icon)
       .setPositiveButton("닫기", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
     }
    })
       .show();
       //*/

    /* 부정 버튼 배치
       new AlertDialog.Builder(DialogButton.this)
       .setTitle("알립니다.")
       .setMessage("대화상자를 열었습니다.")
       .setIcon(R.drawable.icon)
       .setNegativeButton("닫기", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
     }
    })
       .show();
       //*/

       //* null 리스너 작성
       new AlertDialog.Builder(DialogButton.this)
       .setTitle("알립니다.")
       .setMessage("대화상자를 열었습니다.")
       .setIcon(R.drawable.icon)
       .setPositiveButton("닫기", null)
       .show();
       //*/
   }
  });  
 }
}

 


3. 동적 대화상자의 생성

<?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="아래 버튼을 눌러 대화상자를 호출하시오."
    />
<Button
    android:id="@+id/call" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="알림 대화상자"
    />
<Button
    android:id="@+id/call2" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="질문 대화상자"
    />
</LinearLayout>

 

package exam.dialog;

import java.util.*;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ShowDialog extends Activity {
 final static int SampleDialog = 0;
 final static int QuestionDialog = 1;
 
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_showdialog);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    showDialog(SampleDialog);
   }
  });  
  Button btn2 = (Button)findViewById(R.id.call2);
  btn2.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    showDialog(QuestionDialog);
   }
  });  
 }
 
    protected Dialog onCreateDialog(int id) {
     switch (id) {
     case SampleDialog:
      return new AlertDialog.Builder(ShowDialog.this)
   .setTitle("알립니다.")
   .setMessage("대화상자를 열었습니다.")
   .setIcon(R.drawable.icon)
   .setPositiveButton("닫기", null)
   .create();
     case QuestionDialog:
      return new AlertDialog.Builder(ShowDialog.this)
   .setTitle("질문")
   .setMessage("밥 먹었어요?")
   .setPositiveButton("먹었다", null)
   .setNegativeButton("굶었다", null)
   .create();
     }
     return null;
    }

    protected void onPrepareDialog(int id, Dialog dialog) {
     super.onPrepareDialog(id, dialog);
     switch (id) {
     case SampleDialog:
      break;
     case QuestionDialog:
      Calendar calendar = Calendar.getInstance();
      String stime = String.format("%d시 %d분 %d초",
        calendar.get(Calendar.HOUR_OF_DAY),
        calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
      dialog.setTitle(stime);
      break;
     }
    }
}

 


4. 목록 선택 대화 상자
>>>>> res/values/arrys.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country">
        <item>신라</item>
        <item>고구려</item>
        <item>백제</item>
        <item>당나라</item>
        <item>발해</item>
        <item>옥저</item>
        <item>동예</item>
        <item>부여</item>
        <item>대한민국</item>
    </string-array>
    <string-array name="fruits">
        <item>사과</item>
        <item>딸기</item>
        <item>수박</item>
        <item>바나나</item>
        <item>감</item>
        <item>복숭아</item>
        <item>자두</item>
    </string-array>
    <string-array name="foods">
        <item>짜장면</item>
        <item>우동</item>
        <item>짬뽕</item>
        <item>탕수육</item>
    </string-array>
</resources>

 


package exam.dialog;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class SelectDialog1 extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_dialogtest);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    new AlertDialog.Builder(SelectDialog1.this)
    .setTitle("음식을 선택하시오.")
    .setIcon(R.drawable.icon)
    .setItems(R.array.foods,
    // .setItems(new String[] {"짜장면", "우동", "짱뽕", "탕수육" },
     new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int which) {
      String[] foods = getResources().getStringArray(R.array.foods);
      TextView text = (TextView)findViewById(R.id.text);
      text.setText("선택한 음식 = " + foods[which]);
     }
    })
    .setNegativeButton("취소", null)
    .show();
   }
  });  
 }
}

 

 

5. 확인, 취소 버튼이 있는 목록 선택 대화 상자
<?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="아래 버튼을 눌러 대화상자를 호출하시오."
    />
<Button
    android:id="@+id/call" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="대화상자 호출"
    />
</LinearLayout>

 


package exam.dialog;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class SelectDialog2 extends Activity {
 int mSelect = 0;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_dialogtest);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    new AlertDialog.Builder(SelectDialog2.this)
    .setTitle("음식을 선택하시오.")
    .setIcon(R.drawable.icon)
    .setSingleChoiceItems(R.array.foods, mSelect,
      new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int which) {
      mSelect = which;
     }
    })
    .setPositiveButton("확인", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
      String[] foods = getResources().getStringArray(R.array.foods);
      TextView text = (TextView)findViewById(R.id.text);
      text.setText("선택한 음식 = " + foods[mSelect]);
     }
    })
    .setNegativeButton("취소", null)
    .show();
   }
  });  
 }
}

 

 

6. 체크 상자가 있는 대화 상자
package exam.dialog;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class SelectDialog3 extends Activity {
 boolean[] mSelect = { false, false, false, false };
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_dialogtest);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    new AlertDialog.Builder(SelectDialog3.this)
    .setTitle("음식을 선택하시오.")
    .setIcon(R.drawable.icon)
    .setMultiChoiceItems(R.array.foods, mSelect,
      new DialogInterface.OnMultiChoiceClickListener() {
     public void onClick(DialogInterface dialog, int which, boolean isChecked) {
      mSelect[which] = isChecked;
     }
    })
    .setPositiveButton("확인", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
      String[] foods = getResources().getStringArray(R.array.foods);
      TextView text = (TextView)findViewById(R.id.text);
      String result = "선택한 음식 = ";
      for (int i = 0; i < mSelect.length; i++) {
       if (mSelect[i]) {
        result += foods[i] + " ";
       }
      }
      text.setText(result);
     }
    })
    .setNegativeButton("취소", null)
    .show();
   }
  });  
 }
}

 


7.커스텀 대화 상자
<?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"
    android:padding="5pt"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="제품"
    />
<EditText
    android:id="@+id/product" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="수량"
    />
<EditText
    android:id="@+id/number" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:numeric="integer"
    />
<CheckBox
    android:id="@+id/paymethod"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="착불 결제"
    />
</LinearLayout>

 


package exam.dialog;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class OrderDialog extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_dialogtest);

  Button btn = (Button)findViewById(R.id.call);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    final LinearLayout linear = (LinearLayout)
     View.inflate(OrderDialog.this, R.layout.dialog_order, null);
    
    new AlertDialog.Builder(OrderDialog.this)
    .setTitle("주문 정보를 입력하시오.")
    .setIcon(R.drawable.icon)
    .setView(linear)
    .setPositiveButton("확인", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
      EditText product = (EditText)linear.findViewById(R.id.product);
      EditText number = (EditText)linear.findViewById(R.id.number);
      CheckBox paymethod = (CheckBox)linear.findViewById(R.id.paymethod);
      TextView text = (TextView)findViewById(R.id.text);
      text.setText("주문 정보 " + product.getText() + " 상품 " +
        number.getText() + "개." +
        (paymethod.isChecked() ? "착불결제":""));
     }
    })
    .setNegativeButton("취소", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
      TextView text = (TextView)findViewById(R.id.text);
      text.setText("주문을 취소했습니다.");
     }
    })
    .show();
   }
  });  
 }
}

 

 

 

 

Posted by ▶파이팅◀

2011. 3. 21. 13:32 android App

[13-3] 메뉴


[13-3] 메뉴

[01] 메뉴

1. 옵션 메뉴 1

package exam.Input;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class OptionMenu extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView MyText = new TextView(this);
  MyText.setText("메뉴 키를 누르세요.");
  setContentView(MyText);
 }

 public boolean onCreateOptionsMenu(Menu menu) {
  super.onCreateOptionsMenu(menu);
  MenuItem item=menu.add(0,1,0,"짜장");
  item.setIcon(R.drawable.icon);
  item.setAlphabeticShortcut('a');
  //menu.add(0,1,0,"짜장").setIcon(R.drawable.icon).setAlphabeticShortcut('a');
  menu.add(0,2,0,"짬뽕").setIcon(R.drawable.icon);
  SubMenu etc = menu.addSubMenu("기타");
  etc.add(0,3,0,"우동");
  etc.add(0,4,0,"만두");

  return true;
 }

 public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
  case 1:
   Toast.makeText(this,"짜장은 달콤해",Toast.LENGTH_SHORT).show();
   return true;
  case 2:
   Toast.makeText(this,"짬뽕은 매워",Toast.LENGTH_SHORT).show();
   return true;
  case 3:
   Toast.makeText(this,"우동은 시원해",Toast.LENGTH_SHORT).show();
   return true;
  case 4:
   Toast.makeText(this,"만두는 공짜야",Toast.LENGTH_SHORT).show();
   return true;
  }
  return false;
 }
}

 

 

2. XML 기반 옵션 메뉴

<menu xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/jjajang"
  android:title="짜장"
  android:icon="@drawable/icon"
  android:alphabeticShortcut="a"
  />
 <item android:id="@+id/jjambbong"
  android:title="짬뽕"
  android:icon="@drawable/icon"
  />
 <item android:id="@+id/submenu"
  android:title="기타">
  <menu>
   <item android:id="@+id/udong"
    android:title="우동"
    />
   <item android:id="@+id/mandoo"
    android:title="만두"
    />
  </menu>
 </item>
</menu>

 


package exam.Input;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class OptionMenu2 extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView MyText = new TextView(this);
  MyText.setText("메뉴 키를 누르세요.");
  setContentView(MyText);
 }

 public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.menu,menu);
     
     return true;
    }
   
    public boolean onOptionsItemSelected(MenuItem item) {
     switch (item.getItemId()) {
     case R.id.jjajang:
      Toast.makeText(this,"짜장은 달콤해",Toast.LENGTH_SHORT).show();
      return true;
     case R.id.jjambbong:
      Toast.makeText(this,"짬뽕은 매워",Toast.LENGTH_SHORT).show();
      return true;
     case R.id.udong:
      Toast.makeText(this,"우동은 시원해",Toast.LENGTH_SHORT).show();
      return true;
     case R.id.mandoo:
      Toast.makeText(this,"만두는 공짜야",Toast.LENGTH_SHORT).show();
      return true;
     }
     return false;
    }
}

 


3. 체크 박스 옵션 메뉴
android:checkableBehavior="none": 체크 할 수 없는 상태.
android:checkableBehavior="all": 모든 항목을 개별적으로 선택 가능.
android:checkableBehavior="single": 하나의 항목만 선택 가능.


<menu xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/submenu"
  android:title="Sub Menu">
  <menu>
            <group android:id="@+id/checkable_group"
                    android:checkableBehavior="all">
                <item android:id="@+id/bigfont"
                        android:title="BigFont" />
            </group>
            <group android:id="@+id/exclusive_checkable_group"
                    android:checkableBehavior="single">
                <item android:id="@+id/red"
                        android:title="Red"
                        android:checked="true" />
                <item android:id="@+id/green"
                        android:title="Green" />
                <item android:id="@+id/blue"
                        android:title="Blue" />
            </group>
  </menu>
 </item>
</menu>

 


package exam.Input;

import android.app.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class MenuCheck extends Activity {
 Button mBtn;
 
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.input_menucheck);
  mBtn = (Button)findViewById(R.id.button);
 }

 public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.menucheck,menu);
     
     return true;
    }
 
 public boolean onPrepareOptionsMenu(Menu menu) {
  if (mBtn.getTextSize() == 40) {
   menu.findItem(R.id.bigfont).setChecked(true);
  } else {
   menu.findItem(R.id.bigfont).setChecked(false);
  }
  
  int color = mBtn.getTextColors().getDefaultColor();
  
  if (color == Color.RED) {
   menu.findItem(R.id.red).setChecked(true);
  }
  if (color == Color.GREEN) {
   menu.findItem(R.id.green).setChecked(true);
  }
  if (color == Color.BLUE) {
   menu.findItem(R.id.blue).setChecked(true);
  }
  return true;
 }
   
    public boolean onOptionsItemSelected(MenuItem item) {
     switch (item.getItemId()) {
     case R.id.bigfont:
      if (item.isChecked()) {
       mBtn.setTextSize(20);
      } else {
       mBtn.setTextSize(40);
      }
      return true;
     case R.id.red:
   mBtn.setTextColor(Color.RED);
      return true;
     case R.id.green:
   mBtn.setTextColor(Color.GREEN);
      return true;
     case R.id.blue:
   mBtn.setTextColor(Color.BLUE);
      return true;
     }
     return false;
    }
}

 


4. Context menu
   - 뷰를 롱클릭하거나 옵션 메뉴를 선택하면 출력되는 메뉴.


<?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"
    >
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    />

</LinearLayout>

 


package exam.Input;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ContextMenuTest extends Activity {
    Button mBtn;
    EditText mEdit;
    MyImage mImage;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input_contextmenu);
       
        mBtn = (Button)findViewById(R.id.button);
        registerForContextMenu(mBtn);
       
    }
   
    public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
     super.onCreateContextMenu(menu, v, menuInfo);
     
     if (v == mBtn) {
      menu.setHeaderTitle("Button Menu");
         menu.add(0,1,0,"Red");
         menu.add(0,2,0,"Green");
         menu.add(0,3,0,"Blue");
     }

    }
   
    public boolean onContextItemSelected (MenuItem item) {
     switch (item.getItemId()) {
     case 1:
      mBtn.setTextColor(Color.RED);
      return true;
     case 2:
      mBtn.setTextColor(Color.GREEN);
      return true;
     case 3:
      mBtn.setTextColor(Color.BLUE);
      return true;
     return true;
    }
}

 

 

 

 

Posted by ▶파이팅◀


[13-2-D2][UI 설계] ListView, Adapter

[01] ListView

1. 간단한 형태의 ListView

<?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"
    >
<ListView
 android:id="@+id/list" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
 />
</LinearLayout>

 

 

package exam.Widget;

import java.util.*;

import android.app.*;
import android.os.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ListTest extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_listtest);

  //* 데이터 원본 준비
  ArrayList<String> arGeneral = new ArrayList<String>();
  arGeneral.add("김유신");
  arGeneral.add("이순신");
  arGeneral.add("강감찬");
  arGeneral.add("을지문덕");
  //*/
  
  /* 배열로 준비
  String[] arGeneral = {"김유신", "이순신", "강감찬", "을지문덕"};
  //*/

  // 어댑터 준비
  ArrayAdapter<String> Adapter;
  Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arGeneral);

  // 어댑터 연결
  ListView list = (ListView)findViewById(R.id.list);
  list.setAdapter(Adapter);
 }
}

 

 

2. Android SDK Source

 

 


3. 고정된 배열로 부터의 목록 추력

package exam.Widget;

import android.app.*;
import android.os.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ListFromArray extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_listtest);

  ArrayAdapter<CharSequence> Adapter;
  Adapter = ArrayAdapter.createFromResource(this, R.array.country,
    android.R.layout.simple_list_item_1);

  ListView list = (ListView)findViewById(R.id.list);
  list.setAdapter(Adapter);
 }
}

 


4. 속성의 변경

package exam.Widget;

import android.app.*;
import android.graphics.drawable.*;
import android.os.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ListAttr extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_listtest);

  ArrayAdapter<CharSequence> Adapter;
  Adapter = ArrayAdapter.createFromResource(this, R.array.country,
    android.R.layout.simple_list_item_1);

  ListView list = (ListView)findViewById(R.id.list);
  list.setAdapter(Adapter);
  
  list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  list.setDivider(new ColorDrawable(0xffffff00));
  list.setDividerHeight(5);
 }
}

 

 

5. 항목의 편집

<?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">
 <LinearLayout android:orientation="horizontal"
  android:layout_width="fill_parent" android:layout_height="wrap_content">
  <EditText android:id="@+id/newitem" android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:layout_weight="4" />
  <Button android:id="@+id/add" android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:text="Add"
   android:layout_weight="3" />
  <Button android:id="@+id/delete" android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:text="Delete"
   android:layout_weight="3" />
 </LinearLayout>
 <ListView android:id="@+id/list" android:layout_width="fill_parent"
  android:layout_height="fill_parent" />
</LinearLayout>

 

 

package exam.Widget;

import java.util.*;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ListAddDel extends Activity {
 ArrayList<String> Items;
 ArrayAdapter<String> Adapter;
 ListView list;

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

  Items = new ArrayList<String>();
  Items.add("First");
  Items.add("Second");
  Items.add("Third");

  Adapter = new ArrayAdapter<String>(this, android.R.layout.
    simple_list_item_single_choice, Items);
  list = (ListView)findViewById(R.id.list);
  list.setAdapter(Adapter);
  list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

  list.setOnItemClickListener(mItemClickListener);
  findViewById(R.id.add).setOnClickListener(mClickListener);
  findViewById(R.id.delete).setOnClickListener(mClickListener);
 }

 Button.OnClickListener mClickListener = new View.OnClickListener() {
  public void onClick(View v) {
   EditText ed = (EditText)findViewById(R.id.newitem);
   switch (v.getId()) {
   case R.id.add:
    String text = ed.getText().toString();
    if (text.length() != 0) {
     Items.add(text);
     ed.setText("");
     Adapter.notifyDataSetChanged();
    }
    break;
   case R.id.delete:
    int id;
    id=list.getCheckedItemPosition();
    if (id != ListView.INVALID_POSITION) {
     Items.remove(id);
     list.clearChoices();
     Adapter.notifyDataSetChanged();
    }
    break;
   }
  }
 };
 
 AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
  @SuppressWarnings("unchecked")
  public void onItemClick(AdapterView parent, View view, int position, long id) {
   String mes;
   mes = "Select Item = " + Items.get(position);
   Toast.makeText(ListAddDel.this,mes,Toast.LENGTH_SHORT).show();
  }
 };
}

 

 

6. 커스텀 항목의 처리

<?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="60px"
 android:padding="5px">
 <ImageView android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/img"
  android:layout_alignParentLeft="true" />
 <TextView android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/text"
  android:textColor="#00ff00" android:textSize="13pt"
  android:layout_toRightOf="@id/img" />
 <Button android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/btn"
  android:layout_alignParentRight="true" android:text="주문" />
</RelativeLayout>

 


package exam.Widget;

import java.util.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ListIconText extends Activity {
 ArrayList<MyItem> arItem;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_listtest);

  arItem = new ArrayList<MyItem>();
  MyItem mi;
  mi = new MyItem(R.drawable.icon, "삼성 노트북");arItem.add(mi);
  mi = new MyItem(R.drawable.icon, "LG 세탁기");arItem.add(mi);
  mi = new MyItem(R.drawable.icon, "대우 마티즈");arItem.add(mi);

  MyListAdapter MyAdapter = new MyListAdapter(this, R.layout.widget_icontext, arItem);

  ListView MyList;
  MyList=(ListView)findViewById(R.id.list);
  MyList.setAdapter(MyAdapter);
 }
}

//리스트 뷰에 출력할 항목
class MyItem {
 MyItem(int aIcon, String aName) {
  Icon = aIcon;
  Name = aName;
 }
 int Icon;
 String Name;
}

//어댑터 클래스
class MyListAdapter extends BaseAdapter {
 Context maincon;
 LayoutInflater Inflater;
 ArrayList<MyItem> arSrc;
 int layout;

 public MyListAdapter(Context context, int alayout, ArrayList<MyItem> aarSrc) {
  maincon = context;
  Inflater = (LayoutInflater)context.getSystemService(
    Context.LAYOUT_INFLATER_SERVICE);
  arSrc = aarSrc;
  layout = alayout;
 }

 public int getCount() {
  return arSrc.size();
 }

 public String getItem(int position) {
  return arSrc.get(position).Name;
 }

 public long getItemId(int position) {
  return position;
 }

 // 각 항목의 뷰 생성
 public View getView(int position, View convertView, ViewGroup parent) {
  final int pos = position;
  if (convertView == null) {
   convertView = Inflater.inflate(layout, parent, false);
  }
  ImageView img = (ImageView)convertView.findViewById(R.id.img);
  img.setImageResource(arSrc.get(position).Icon);

  TextView txt = (TextView)convertView.findViewById(R.id.text);
  txt.setText(arSrc.get(position).Name);

  Button btn = (Button)convertView.findViewById(R.id.btn);
  btn.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    String str = arSrc.get(pos).Name + "를 주문합니다.";
    Toast.makeText(maincon, str, Toast.LENGTH_SHORT).show();
   }
  });

  return convertView;
 }
}

 


7. 항목 View의 조합

<?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="100px"
    android:gravity="bottom"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft = "10px"
    android:layout_marginRight = "15px"
    android:id="@+id/text"
    android:textColor="#ffffff"
    android:textSize="20px"
    android:layout_gravity="bottom"
    />
<EditText
 android:id="@+id/edit" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_marginLeft = "10px"
    android:layout_marginRight = "15px"
    android:textColor="#000000"
    android:textSize="20px"
    />
</LinearLayout>

 


<?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="70px"
    >
<Button
    android:layout_width="120px"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/btn" 
    android:text="Button"
    />
<ImageView android:layout_width="50px"
 android:layout_height="50px"
 android:id="@+id/img"
 android:layout_marginRight="10px"
 />
</LinearLayout>

 

 

package exam.Widget;

import java.util.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class ListOfViews extends Activity {
    ArrayList<ListItem> arItem;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_listtest);
       
        arItem = new ArrayList<ListItem>();
        arItem.add(new ListItem(0,"제목","입력내용","",0));
        arItem.add(new ListItem(1,"","","push",R.drawable.icon));
        arItem.add(new ListItem(0,"이름을 입력하시오.","니 이름","",0));
        arItem.add(new ListItem(0,"나이도 입력하시오.","몇살이니","",0));
        arItem.add(new ListItem(1,"","","누르시오",R.drawable.icon));
        arItem.add(new ListItem(1,"","","업로드",R.drawable.icon));
        arItem.add(new ListItem(0,"주소","어디 사니?","",0));

        MultiAdapter MyAdapter = new MultiAdapter(this, arItem);
       
        ListView MyList;
        MyList=(ListView)findViewById(R.id.list);
        MyList.setAdapter(MyAdapter);
    }
}

class ListItem {
 ListItem(int aType, String aText, String aEditText, String aBtnText, int aIconRes) {
  Type = aType;
  Text = aText;
  EditText = aEditText;
  BtnText = aBtnText;
  IconRes = aIconRes;
 }
 int Type;
 String Text;
 String EditText;
 String BtnText;
 int IconRes;
}

class MultiAdapter extends BaseAdapter {
 LayoutInflater mInflater;
 ArrayList<ListItem> arSrc;

 public MultiAdapter(Context context, ArrayList<ListItem> arItem) {
  mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  arSrc = arItem;
 }

 public int getCount() {
  return arSrc.size();
 }

 public ListItem getItem(int position) {
  return arSrc.get(position);
 }


 public long getItemId(int position) {
  return position;
 }
 
 public int getItemViewType(int position) {
  return arSrc.get(position).Type;
 }
 
 // getView가 생성하는 뷰의 개수를 리턴한다. 항상 같은 뷰를 생성하면 1을 리턴한다.
 // 이 메소드에서 개수를 제대로 조사해 주지 않으면 다운된다.
 public int getViewTypeCount() {
  return 2;
 }

 public View getView(int position, View convertView, ViewGroup parent) {
  // 최초 호출이면 항목 뷰를 생성한다.
  // 타입별로 뷰를 다르게 디자인할 수 있으며 높이가 달라도 상관없다.
  if (convertView == null) {
   int res = 0;
   switch (arSrc.get(position).Type) {
   case 0:
    res = R.layout.widget_textedit;
    break;
   case 1:
    res = R.layout.widget_btnicon;
    break;
   }
   convertView = mInflater.inflate(res, parent, false);
  }
  
  // 항목 뷰를 초기화한다.
  switch (arSrc.get(position).Type) {
  case 0:
   TextView txt = (TextView)convertView.findViewById(R.id.text);
   txt.setText(arSrc.get(position).Text);
   EditText edit = (EditText)convertView.findViewById(R.id.edit);
   edit.setText(arSrc.get(position).EditText);
   break;
  case 1:
   Button btn = (Button)convertView.findViewById(R.id.btn);
   btn.setText(arSrc.get(position).BtnText);
   ImageView img = (ImageView)convertView.findViewById(R.id.img);
   img.setImageResource(arSrc.get(position).IconRes);
   break;
  }

  return convertView;
 }
}

 

 

8. ListActivity

package exam.Widget;

import java.util.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class ListOnly extends ListActivity {
 ArrayList<String> arGeneral;
 protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);

  setContentView(R.layout.listActivity);

  arGeneral = new ArrayList<String>();
  arGeneral.add("김유신");
  arGeneral.add("이순신");
  arGeneral.add("강감찬");
  arGeneral.add("을지문덕");

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

  setListAdapter(Adapter);
 }

 public void onListItemClick(ListView list, View view, int position, long id) {
  String mes;
  mes = "Select Item = " + arGeneral.get(position);
  Toast.makeText(ListOnly.this,mes,Toast.LENGTH_SHORT).show();
 }
}

 

 

[03] AdapterView

1. Spinner
arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country">
        <item>신라</item>
        <item>고구려</item>
        <item>백제</item>
        <item>당나라</item>
        <item>발해</item>
        <item>옥저</item>
        <item>동예</item>
        <item>부여</item>
        <item>대한민국</item>
    </string-array>
    <string-array name="fruits">
        <item>사과</item>
        <item>딸기</item>
        <item>수박</item>
        <item>바나나</item>
        <item>감</item>
        <item>복숭아</item>
        <item>자두</item>
    </string-array>
    <string-array name="foods">
        <item>짜장면</item>
        <item>우동</item>
        <item>짬뽕</item>
        <item>탕수육</item>
    </string-array>
</resources>

 


<?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/mytext"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="먹고 싶은 과일을 선택하세요."
    />
<Spinner
 android:id="@+id/myspinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

 

 

package exam.Widget;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
import exam.AndroidExam.*;

public class SpinnerTest extends Activity {
 ArrayAdapter<CharSequence> adspin;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_spinnertest);

  Spinner spin = (Spinner)findViewById(R.id.myspinner);
  spin.setPrompt("과일을 고르세요.");

  adspin = ArrayAdapter.createFromResource(this, R.array.fruits,
    android.R.layout.simple_spinner_item);
  adspin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spin.setAdapter(adspin);

  spin.setOnItemSelectedListener(new OnItemSelectedListener() {
   public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(SpinnerTest.this,adspin.getItem(position) + "는 맛있다.",
      Toast.LENGTH_SHORT).show();
   }
   public void onNothingSelected(AdapterView<?> parent) {
   }
  });
 }
}

 

 

2. Grid

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/grid" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
 />

 


package exam.Widget;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
import exam.AndroidExam.*;

public class GridTest extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_gridtest);

  GridView grid = (GridView)findViewById(R.id.grid);
  ImageAdapter Adapter = new ImageAdapter(this);
  grid.setAdapter(Adapter);
  
  grid.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(GridTest.this, position + "번째 그림 선택",
      Toast.LENGTH_SHORT).show();
   }
  });
 }
}

class ImageAdapter extends BaseAdapter {
 private Context mContext;

 int[] picture = { R.drawable.pride, R.drawable.dog, R.drawable.cloud };

 public ImageAdapter(Context c) {
  mContext = c;
 }

 public int getCount() {
  return 100;
 }

 public Object getItem(int position) {
  return picture[position % 3];
 }

 public long getItemId(int position) {
  return position;
 }

 public View getView(int position, View convertView, ViewGroup parent) {
  ImageView imageView;
  if (convertView == null) {
   imageView = new ImageView(mContext);
   imageView.setLayoutParams(new GridView.LayoutParams(45, 45));
   imageView.setAdjustViewBounds(false);
   imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
   imageView.setPadding(8, 8, 8, 8);
  } else {
   imageView = (ImageView) convertView;
  }

  imageView.setImageResource(picture[position % 3]);

  return imageView;
 }
}

 

 

3. Gallery

<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/gallery"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:spacing="5px"
 android:animationDuration="1500"
/>

 

 

package exam.Widget;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import exam.AndroidExam.*;

public class GalleryTest extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.widget_gallerytest);

  Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter2(this));
 }
}

class ImageAdapter2 extends BaseAdapter {
 private Context mContext;
 private int[] mImageIds = {
   R.drawable.ccdam,
   R.drawable.soyang2,
   R.drawable.ududong,
   R.drawable.zipdarigol,
   R.drawable.dongul,
   R.drawable.lotteworld,
 };

 public ImageAdapter2(Context c) {
  mContext = c;
 }

 public int getCount() {
  return mImageIds.length;
 }

 public Object getItem(int position) {
  return mImageIds[position];
 }

 public long getItemId(int position) {
  return position;
 }

 public View getView(int position, View convertView, ViewGroup parent) {
  ImageView imageView;
  
  if (convertView == null) {
   imageView = new ImageView(mContext);
  } else {
   imageView = (ImageView)convertView;
  }

  imageView.setImageResource(mImageIds[position]);
  imageView.setScaleType(ImageView.ScaleType.FIT_XY);
  imageView.setLayoutParams(new Gallery.LayoutParams(136, 88));

  return imageView;
 }
}

 

 

 

Posted by ▶파이팅◀

블로그 이미지
Let's start carefully from the beginning
▶파이팅◀

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.11
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

최근에 올라온 글

최근에 달린 댓글

글 보관함