안드로이드 학습을 하다가 다시 그만두다가를 반복했는데 필요에 의해서 다시 학습을 시작하고 있다.

1차 목표는 리스트 뷰를 사용하여 아이템을 등록하고, 해당 아이템의 상태를 변경하는 간단한 앱을 만들어서 마켓에 올리는 것이다.



[그림1] 아이템의 상태 변경





[그림2] 아이템의 상태 변경


개발중에 가장 문제가 되었던것중에 하나가 

우선, [그림1]에서와 같이 아이템의 체크박스에 체크를 하고, 구매 상태를 변경한 후에 EditText에 포커싱이 되어서 소프트 키보드가 오픈이 되는 순간

[그림1]에서 변경했던 상태가 [그림2]에서처럼 유지가 되지 않는것이었다.





This example will show how to transfer URI data from an Activity to another Activity.

Please download the sample projects and import these projects into your IDE. ^^


IntentsLabSubmit.zip


We can populate an AdapterView such as Listview or GridView by binding the AdapterView instance to an Adapter.

At this example, We will learn to implement simple list using a ListView and BaseAdapter basically.


The steps to implement ListView are the following.


1. Define the XML Layout to display data in the view.


2. Define Java beans Class to save data.


3. Define the view group so that Listview is populated with data. 


4. Define Adapter which is charge of the role of the data management.

: Adater is an interface whose implementations provide data and the display of that data used by the Listview.


5. Define Listview to display on the screen and Listener being called when data is selected.




Defining the XML Layout to display data in the view.

==== sports_item.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="horizontal" >

    

<TextView 

   android:id="@+id/sportsName"

   android:layout_width="match_parent"

   android:layout_height="wrap_content"

   android:layout_weight="1"

   android:text="야구"

   />

<TextView 

   android:id="@+id/description"

   android:layout_width="match_parent"

   android:layout_height="wrap_content"

   android:layout_weight="1"

   android:text="야구"

   />

<TextView 

   android:id="@+id/memberCount"

   android:layout_width="match_parent"

   android:layout_height="wrap_content"

   android:layout_weight="1"

   android:text="야구"

   />

</LinearLayout>




Defining java beans class to save data.

==== SportsItem.java ====


package com.example.samplelistviewsports;


public class SportsItem {

private String sportsName;

private String description;

private String memberCount;

public SportsItem(String sportsName, String description, String memberCount) {

super();

this.sportsName = sportsName;

this.description = description;

this.memberCount = memberCount;

}


public String getSportsName() {

return sportsName;

}


public void setSportsName(String sportsName) {

this.sportsName = sportsName;

}


public String getDescription() {

return description;

}


public void setDescription(String description) {

this.description = description;

}


public String getMemberCount() {

return memberCount;

}


public void setMemberCount(String memberCount) {

this.memberCount = memberCount;

}

}




Defining the view group so that Listview populated with data.

==== SportsItemView.java ====

package com.example.samplelistviewsports;


import android.content.Context;

import android.view.LayoutInflater;

import android.widget.LinearLayout;

import android.widget.TextView;


public class SportsItemView extends LinearLayout {


private TextView sportsName;

private TextView description;

private TextView memberCount;

public SportsItemView(Context context, SportsItem item) {

super(context);

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

inflater.inflate(R.layout.sports_items, this, true);

sportsName = (TextView)findViewById(R.id.sportsName);

description = (TextView)findViewById(R.id.description);

memberCount = (TextView)findViewById(R.id.memberCount);

sportsName.setText(item.getSportsName());

description.setText(item.getDescription());

memberCount.setText(item.getMemberCount());

}


}



Defining ListView Adapter.

==== SportsItemViewAdapter.java ====

package com.example.samplelistviewsports;


import java.util.ArrayList;

import java.util.List;


import android.content.Context;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;


public class SportsListViewAdapter extends BaseAdapter{

private List<SportsItem> items = new ArrayList<SportsItem>();

private Context context;

public SportsListViewAdapter(Context context) {

super();

this.context = context;

}


public void addItem(SportsItem item){

items.add(item);

}

@Override

public int getCount() {

// TODO Auto-generated method stub

return items.size();

}


@Override

public Object getItem(int arg0) {

// TODO Auto-generated method stub

return items.get(arg0);

}


@Override

public long getItemId(int position) {

// TODO Auto-generated method stub

return 0;

}


@Override

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

SportsItemView itemView = null;

if(convertView == null){

itemView = new SportsItemView(context, items.get(position));

}else{

itemView = (SportsItemView)convertView;

}

return itemView;

}


}

--> getView method is the most important method in this adapter. The view being returned from this method is displayed on the screen as one item.



Defining Listview to display on the screen.

==== SportListView.java ====

package com.example.samplelistviewsports;


import android.content.Context;

import android.widget.BaseAdapter;

import android.widget.ListView;


public class SportListView extends ListView {


public SportListView(Context context) {

super(context);

// TODO Auto-generated constructor stub

}

public void setAdapter(BaseAdapter adapter){

super.setAdapter(adapter);

}


}





Making a codes to excute the app in the MainActivity.

==== MainActivity.java ====

package com.example.samplelistviewsports;


import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.ViewGroup;

import android.view.ViewGroup.LayoutParams;


public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

SportsListViewAdapter adapter = new SportsListViewAdapter(this);

adapter.addItem(new SportsItem("야구", "9명이 하는 베이스볼 게임", "9명"));

adapter.addItem(new SportsItem("축구", "11명이 하는 멋진 게임", "11명"));

SportsListView listView = new SportsListView(this);

listView.setAdapter(adapter);

                listView.setOnItemClickListener(new OnItemClickListener() {


@Override

public void onItemClick(AdapterView<?> parent, View view, int position,

long arg3) {

ListView listView = (ListView) parent;

//SportsItem item = (SportsItem)listView.getItemAtPosition(position);

SportsItem item = (SportsItem)adapter.getItem(position);

                                Toast.makeText(getBaseContext(), item.getSportsName(), Toast.LENGTH_LONG).show();

}

});

LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

setContentView(listView, params);

}


@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}


}




Below is the screen executed this app.

























'Android > Layout' 카테고리의 다른 글

Set borders by using the LinearLayout  (0) 2014.02.01

We can remove the default title bar provided in the system. 

There are two ways like the following examples.


The first way,

==== MainActivity.java ====

package com.example.samplebitmapwidget;


import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.Window;


public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_main);

}

}


: we can remove the title bar by calling requestWindowFeature() method like the above. This method should be called before being called setContentView() method.




The second way,

==== AndroidManifest.xml ====

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

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

    package="com.example.samplebitmapwidget"

    android:versionCode="1"

    android:versionName="1.0" >


    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="18" />


    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@android:style/Theme.Light.NoTitleBar" >

        <activity

            android:name="com.example.samplebitmapwidget.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>


</manifest>


: We can remove the title bar by specifying "@android:style/Theme.Light.NoTitleBar" as a value of the "android:theme" attribute.



the following is the feature removed the default title.



It's important that we specify the appropriate input type that the user expects,such as an email address, phone number, or just plain text when they enter some text in every text field.


We can specify the appropriate input type like the following.

==== activity_main.xml ====

<LinearLayout 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="#ffcccccc"

android:orientation="vertical" >

<!-- The button for closing the keypad -->

<Button 

   android:id="@+id/btnCloseKeyPad"

   android:layout_width="match_parent"

   android:layout_height="wrap_content"

   android:text="closing keypad"

   />

<TextView

android:id="@+id/caption01"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: text|textCapWords"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox01"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="text|textCapWords

/>

<TextView

android:id="@+id/caption02"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: number|numberSigned|numberDecimal"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox02"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="number|numberSigned|numberDecimal

/>

<TextView

android:id="@+id/caption03"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: textEmailAddress"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox03"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="textEmailAddress"

/>

<TextView

android:id="@+id/caption04"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: textPassword"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox04"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="textPassword"

/>

<TextView

android:id="@+id/caption05"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: phone"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox05"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="phone"

/>

<TextView

android:id="@+id/caption06"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: date"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox06"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="date"

/>

<TextView

android:id="@+id/caption07"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#ff0000ff"

android:text="inputType: time"

android:textStyle="bold"

android:textSize="18dp" 

android:textColor="#ffffffff"

/>

<EditText

android:id="@+id/editTextBox07"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="10px"

android:textSize="16dp"

android:inputType="time"

/>

</LinearLayout>


: We can specify the input type for out text field by adding the android:inputType attribute to the EditText element.


Here are several possible values documented with the android:inputType attribute.



'Android > ㄴ on-screen keyboard' 카테고리의 다른 글

Closing an on-screen keyboard  (0) 2014.02.07

For example, we should let us close an on-screen keyboard, after we log in successfully.

In that case, We can close the keybord programmatically. 


==== MainActivity.java ====

package com.example.samplekeypad;


import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.inputmethod.InputMethodManager;

import android.widget.Button;

import android.widget.Toast;


public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button btnCloseKeypad = (Button)findViewById(R.id.btnCloseKeyPad);

btnCloseKeypad.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

/**

* We can close the on-screen keyboard by using InputMethodManager.

*/

InputMethodManager inputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);

inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);


Toast.makeText(getBaseContext(), "스크린 키보드를 닫습니다.", Toast.LENGTH_SHORT).show();

}

});

}


@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}


}


: We can close an on-screen keyboard by calling hideSoftInputFromWindow() method in InputMethodManager Class.


'Android > ㄴ on-screen keyboard' 카테고리의 다른 글

Specifying The Keyboard Type  (0) 2014.02.07

In this posting, we can learn how to use the Action Bar, simply. 


Action items appear directly in the action bar with an icon or text are known as action buttons. 

Actions that can't fit in the action bar or aren't important enough are hidden in the action overflow.


Now, here's how to add the Action Bar.


1. Specify the Actions in XML

First, we should define in an XML menu resource for all action buttons and other items available in the action overflow. 

we create a new XML file in our project's 'res/menu/' directory.

==== res/menu/main.xml ====

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


    <item android:id="@+id/menu_refresh"

        android:title="@string/menu_refresh"

        android:icon="@drawable/menu_refresh"

        android:orderInCategory="101"

        android:showAsAction="always" />


  <item android:id="@+id/menu_search"

        android:title="@string/menu_search"

        android:icon="@drawable/menu_search"

        android:orderInCategory="102"

        android:showAsAction="always|withText" />

    

  <item android:id="@+id/menu_settings"

        android:title="@string/menu_settings"

        android:icon="@drawable/menu_settings"

        android:orderInCategory="103"

        android:showAsAction="never" />

</menu>

: Add an <item> element for each item you want to include in the action bar.

In icon case, we can use icons provided in "http://developer.android.com/design/downloads/index.html#action-bar-icon-pack"


2. Add the Actions to the Action Bar

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

: We should implement onCreateOptionsMenu() callback method in our activity to inflate the menu resource into the given Menu object.


3. Respond to Action Buttons

/**

* This method is called automatically, when ActionBar's menu is selected.

* @param item

* @return

*/

@Override

public boolean onOptionsItemSelected(MenuItem item)

{

switch(item.getItemId()){

case R.id.menu_refresh:

text01.setText("새로고침 메뉴 선택!!");

return true;

case R.id.menu_search:

text01.setText("검색 메뉴 선택!!");

return true;

case R.id.menu_settings:

text01.setText("설정 메뉴 선택");

return true;

}

return super.onOptionsItemSelected(item);

}

: When the user presses one of the action buttons, the Android system calls our activity's onOptionsItemSelected() callback method.

We can call getItemId() method to determine which item was pressed. And then The returned ID can match the value we declared in the corresponding <item> element's android:id attributes.



The result let us run the application is the following.




'Android > Activity' 카테고리의 다른 글

Staring Another Activity  (0) 2014.02.03

In this section, I'll start another Activity when I click the the Send button in Main Activity.


Let's see the following.



1. Respond to the Send Button.

==== activity_main.xml ====

<LinearLayout 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:orientation="horizontal"
   >
 <EditText 
     android:id="@+id/message"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:hint="Enter a message"
     android:layout_weight="1"
     />
 <Button 
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Send"
     android:textSize="20sp"
     android:onClick="sendMessage"
     />
</LinearLayout>

: the android:onClick attribute's value, "sendMessage" is the name of a method in MainActivity that the system calls when the user click the button.


2. Build an Intent

==== MainActivity.java ====

public void sendMessage(View view)
 {
  Intent intent = new Intent(getBaseContext(), DisplayMessageActivity.class);
  
  editText = (EditText)findViewById(R.id.message);
  String message = editText.getText().toString();
  
  intent.putExtra(EXTRA_MESSAGE, message);
  startActivity(intent); 

 }

- Add the corresponding method in the MainActivity.

- Inside the sendMessage method, create an Intent to start an activity called DisplaymessageActivity.



3. Create the second Activity

==== DisplayMessageActivity.java ====

protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  
  // Get the message from the Intent  
  Intent intent = getIntent();
  String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
  
  TextView textView = new TextView(this);
  textView.setTextSize(40);
  textView.setText(message);
 
 // Set the Textview as an activity layout
  setContentView(textView);
}

- We can now run the app.

- When it opens, type a message in the textfield, click the button, and the message in the textfield appears on the second activity.

'Android > Activity' 카테고리의 다른 글

Action Bar: Adding Action Buttons  (0) 2014.02.03

We can set the background color in the LinearLayout, but can't find the attribute about a border. 

Now Let's see the following about setting borders around the LinearLayout.


The First way is to use Shape Object.


==== header_border.xml ====

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

 <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">

   <padding android:left="10sp" android:right="10sp" android:top="10sp" android:bottom="10sp"/>

  <solid android:color="@android:color/transparent"/>

   <stroke

    android:width="1sp"

    android:color="#000000" />

   

 </shape>

: Define header_border.xml like this. Then Save it into '/res/drawable-mdpi'



==== activie_main.xml ====

<LinearLayout 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:orientation="vertical"

    android:background="ffffff"

     >

     <LinearLayout 

         android:layout_width="match_parent"

         android:layout_height="wrap_content"

         android:orientation="horizontal"

         android:background="@drawable/header_border"

         >

       <ImageButton 

           android:id="@+id/side_menu"

           android:layout_width="40sp"

           android:layout_height="40sp"

           android:background="@drawable/icon_list"

           android:contentDescription="사이드 메뉴"

           android:layout_marginTop="5sp"

           />

        <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="아이템 목록"

        android:textSize="20sp" 

        android:layout_marginTop="5sp"

        android:layout_weight="1"

        android:gravity="center"

        />

       <ImageButton 

           android:id="@+id/user_config"

           android:layout_width="37sp"

           android:layout_height="37sp"

           android:background="@drawable/icon_config"

           android:contentDescription="사용자 설정"

           android:layout_marginTop="5sp"

           android:layout_marginRight="5sp"

           />

     </LinearLayout>

: Set the reference of header_border object as a background attribute's value. then We can find borders around the LinearLayout.


But I'd like to do that only the LinearLayout appears only bottom border.

We can see the following for it.


 ==== activity_main.xml ====

<LinearLayout 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:orientation="vertical"

    android:background="ffffff"

     >

     <LinearLayout 

         android:layout_width="match_parent"

         android:layout_height="wrap_content"

         android:orientation="horizontal"

         android:background="f0fff0"

         android:padding="10sp"

         >

       <ImageButton 

           android:id="@+id/side_menu"

           android:layout_width="40sp"

           android:layout_height="40sp"

           android:background="@drawable/icon_list"

           android:contentDescription="사이드 메뉴"

          

           />

        <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="아이템 목록"

        android:textSize="20sp" 

        android:layout_marginTop="5sp"

        android:layout_weight="1"

        android:gravity="center"

        />

       <ImageButton 

           android:id="@+id/user_config"

           android:layout_width="37sp"

           android:layout_height="37sp"

           android:background="@drawable/icon_config"

           android:contentDescription="사용자 설정"

          

           />

     </LinearLayout>

     <!-- This is LinearLayout for bottom border. -->

     <LinearLayout 

         android:layout_width="match_parent"

         android:layout_height="2dp"

         android:background="000000"

         >

         

     </LinearLayout>

    

</LinearLayout>

: We add a LinearLayout for bottom border. It has no child view. It just has layout_height "2dp" and background "000000" as values of the attributes.

 

We can see the bottom border like this.



'Android > Layout' 카테고리의 다른 글

Filling an Listview with data  (0) 2014.02.17

+ Recent posts

출처: http://large.tistory.com/23 [Large]