「Android」ListView と ArrayAdapter の使い方

1.activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/list_view1″
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</ListView>
</LinearLayout>

 

2.MainActivity.java
package com.changfa.demoViewLst;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

private String[] viewListData = {“名前:山田次郎","学歴:大学","会社:○○会社",出身:大崎","age:32″};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//ListView取得
ListView listView = (ListView) findViewById(R.id.list_view1);
//ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, viewListData);
//ArrayAdapterでデータを設定
listView.setAdapter(adapter);

//イベント追加
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String info = viewListData[position];
Toast.makeText(MainActivity.this, info, 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;
}

}

Android

Posted by arkgame