Android 開発 第一回

  • RSS リーダの作成

以下の記事を参考に作成。
というか、ほぼそのままです…。

全然、整理をつけていないので、そのうち纏めます…。


  • メイン画面(レイアウト)
<?xml version="1.0" encoding="utf-8"?>
<!-- mainアクティビティ用 -->
<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="@android:id/list"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content" />
	<!-- リストが空のときに表示 -->
</LinearLayout>

  • 行(レイアウト)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	android:id="@+id/item_container"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TextView
		android:id="@+id/item_title"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:textColor="#ffffff"
		android:textSize="18sp"
		android:lines="1" />
	<TextView
		android:id="@+id/item_descr"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:lines="2"
		android:ellipsize="end" />
</LinearLayout>

  • 詳細画面(レイアウト)
<?xml version="1.0" encoding="utf-8"?>
<!-- item_detail.xml -->
<LinearLayout
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TextView
		android:id="@+id/item_detail_title"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceLarge"
		android:background="@android:drawable/dark_header" />
	<TextView
		android:id="@+id/item_detail_descr"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
</LinearLayout>

  • メイン画面
package jp.co.persil.rss;

import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class PersilRSS extends ListActivity
{
	// ------------------------------------------------------------
	// メンバ
	// ------------------------------------------------------------
	private ArrayList<Item> mItems;
	private RssListAdapter  mAdapter;
	
	// ------------------------------------------------------------
	// 定数
	// ------------------------------------------------------------
	public static final String RSS_FEED_URL     = "http://itpro.nikkeibp.co.jp/rss/ITpro.rdf";
	public static final int    MENU_ITEM_RELOAD = Menu.FIRST;
	
	// ------------------------------------------------------------
	// 【EVENT】Activity 作成
	// ------------------------------------------------------------
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		// スーパークラスの呼出
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		// Itemオブジェクトを保持するためのリストを生成し、アダプタに追加する
		mItems   = new ArrayList<Item>();
		mAdapter = new RssListAdapter(this, mItems);
		
		// タスクを起動する
		RssParserTask task = new RssParserTask(this, mAdapter);
		task.execute(RSS_FEED_URL);
	}
	
	// ------------------------------------------------------------
	// 【EVENT】リストの項目を選択した時の処理
	// ------------------------------------------------------------
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		Item item = mItems.get(position);
		Intent intent = new Intent(this, ItemDetailActivity.class);
		intent.putExtra("TITLE", item.getTitle());
		intent.putExtra("DESCRIPTION", item.getDescription());
		startActivity(intent);
	}
	
	// ------------------------------------------------------------
	// 【EVENT】オプションボタン追加
	// ------------------------------------------------------------
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);
		// デフォルトではアイテムを追加した順番通りに表示する
		menu.add(0, MENU_ITEM_RELOAD, 0, "更新");
		return result;
	}
	
	// ------------------------------------------------------------
	// 【EVENT】MENUの項目を押したときの処理
	// ------------------------------------------------------------
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			// 更新
			case MENU_ITEM_RELOAD:
				// アダプタを初期化し、タスクを起動する
				mItems   = new ArrayList<Item>();
				mAdapter = new RssListAdapter(this, mItems);
				// タスクはその都度生成する
				RssParserTask task = new RssParserTask(this, mAdapter);
				task.execute(RSS_FEED_URL);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	// ------------------------------------------------------------
	// 【METHOD】ツリービューアイテムを追加
	// ------------------------------------------------------------
	public void setListAdapter( RssListAdapter mAdapter)
	{
		// アダプタをリストビューにセットする
		ListView lv = (ListView)findViewById(android.R.id.list);
		lv.setAdapter(mAdapter);
	}
}

  • 行へのアイテム管理用
package jp.co.persil.rss;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

//RssListAdapter.java
public class RssListAdapter extends ArrayAdapter<Item>
{
	// ------------------------------------------------------------
	// メンバ
	// ------------------------------------------------------------
	private LayoutInflater mInflater;
	private TextView       mTitle;
	private TextView       mDescr;
	
	// ------------------------------------------------------------
	// コンストラクタ
	// ------------------------------------------------------------
	public RssListAdapter(Context context, List<Item> objects)
	{
		super(context, 0, objects);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	// ------------------------------------------------------------
	// 【METHOD】1行毎に View を作成する
	// ------------------------------------------------------------
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View view = convertView;

		if (convertView == null)
		{
			view = mInflater.inflate(R.layout.item_row, null);
		}
		
		// 現在参照しているリストの位置からItemを取得する
		Item item = this.getItem(position);
		if (item != null)
		{
			// Itemから必要なデータを取り出し、それぞれTextViewにセットする
			String title = item.getTitle().toString();
			mTitle = (TextView) view.findViewById(R.id.item_title);
			mTitle.setText(title);
			String descr = item.getDescription().toString();
			mDescr = (TextView) view.findViewById(R.id.item_descr);
			mDescr.setText(descr);
		}
		return view;
	}
}

  • 画面への設定用ルーチン
package jp.co.persil.rss;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Xml;

public class RssParserTask extends AsyncTask<String, Integer, RssListAdapter>
{
	// ------------------------------------------------------------
	// メンバ
	// ------------------------------------------------------------
	private PersilRSS      mActivity;
	private RssListAdapter mAdapter;
	private ProgressDialog mProgressDialog;
	
	// ------------------------------------------------------------
	// コンストラクタ
	// ------------------------------------------------------------
	public RssParserTask(PersilRSS activity, RssListAdapter adapter)
	{
		mActivity = activity;
		mAdapter  = adapter;
	}
	
	// ------------------------------------------------------------
	// 【Method】メインスレッドから execute 呼出時に実行される
	// 【Thread】メインスレッド
	// ------------------------------------------------------------
	@Override
	protected void onPreExecute()
	{
		// プログレスバーを表示する
		mProgressDialog = new ProgressDialog(mActivity);
		
		mProgressDialog.setMessage("Now Loading...");
		mProgressDialog.show();
	}
	
	// ------------------------------------------------------------
	// 【Method】メインスレッドから execute 呼出時に実行される
	// 【Thread】バックグラウンド
	// ------------------------------------------------------------
	@Override
	protected RssListAdapter doInBackground(String... params)
	{
		RssListAdapter result = null;
		try
		{
			// HTTP経由でアクセスし、InputStreamを取得する
			URL         url = new URL(params[0]);
			InputStream is  = url.openConnection().getInputStream();
			
			result = parseXml(is);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		// ここで返した値は、onPostExecuteメソッドの引数として渡される
		return result;
	}
	
	// ------------------------------------------------------------
	// 【Method】doInBackground のメソッド完了後に実行される
	// 【Thread】メインスレッド
	// ------------------------------------------------------------
	@Override
	protected void onPostExecute(RssListAdapter result)
	{
		mProgressDialog.dismiss();
		mActivity.setListAdapter(result);
	}
	
	// ------------------------------------------------------------
	// 【Method】XML をパースする
	// ------------------------------------------------------------
	public RssListAdapter parseXml(InputStream is) throws IOException, XmlPullParserException
	{
		// XML パーサをインスタンス化
		XmlPullParser parser = Xml.newPullParser();
		
		// try-catch 開始
		try
		{
			// 引数で受け取ったストリームを設定
			parser.setInput(is, null);
			
			// イベントタイプを設定
			int eventType    = parser.getEventType();
			
			// 初期化
			Item currentItem = null;
			
			// ドキュメントの最後まで繰り返し
			while (eventType != XmlPullParser.END_DOCUMENT)
			{
				String tag = null;
				switch (eventType)
				{
					// 開始タグ
					case XmlPullParser.START_TAG:
						tag = parser.getName();
						if (tag.equals("item"))
						{
							currentItem = new Item();
						}
						else if (currentItem != null)
						{
							if (tag.equals("title"))
							{
								currentItem.setTitle(parser.nextText());
							}
							else if (tag.equals("description"))
							{
								currentItem.setDescription(parser.nextText());
							}
						}
						break;
						
					// 終了タグ
					case XmlPullParser.END_TAG:
						tag = parser.getName();
						if (tag.equals("item"))
						{
							mAdapter.add(currentItem);
						}
						break;
				}
				eventType = parser.next();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return mAdapter;
	}
}

  • アイテム管理用
package jp.co.persil.rss;

public class Item
{
	// ------------------------------------------------------------
	// メンバ
	// ------------------------------------------------------------
	private CharSequence mTitle;
	private CharSequence mDescription;
	
	// ------------------------------------------------------------
	// コンストラクタ
	// ------------------------------------------------------------
	public Item()
	{
		mTitle       = "";
		mDescription = "";
	}
	
	// ------------------------------------------------------------
	// 【getter】Description
	// ------------------------------------------------------------
	public CharSequence getDescription()
	{
		return mDescription;
	}
	
	// ------------------------------------------------------------
	// 【setter】Description
	// ------------------------------------------------------------
	public void setDescription(CharSequence description)
	{
		mDescription = description;
	}
	
	// ------------------------------------------------------------
	// 【getter】Title
	// ------------------------------------------------------------
	public CharSequence getTitle()
	{
		return mTitle;
	}
	
	// ------------------------------------------------------------
	// 【setter】Title
	// ------------------------------------------------------------
	public void setTitle(CharSequence title)
	{
		mTitle = title;
	}
}

  • 行単位のアクティビティ

package jp.co.persil.rss;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ItemDetailActivity extends Activity
{
	// ------------------------------------------------------------
	// メンバ
	// ------------------------------------------------------------
	private TextView mTitle;
	private TextView mDescr;
	
	// ------------------------------------------------------------
	// コンストラクタ
	// ------------------------------------------------------------
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_detail);
		
		Intent intent = getIntent();
		
		String title = intent.getStringExtra("TITLE");
		mTitle = (TextView) findViewById(R.id.item_detail_title);
		mTitle.setText(title);
		String descr = intent.getStringExtra("DESCRIPTION");
		mDescr = (TextView) findViewById(R.id.item_detail_descr);
		mDescr.setText(descr);
	}
}
最終更新:2012年02月26日 16:06