2012年3月17日 星期六

TabView Olympic Sports



A sport term dictionay:

1. 採用 TabView:Two tabs (Cq_SportsTapActivity.java + main.xml)

2. One for Winter (WinterSports.java + WinterAdapter.java 定義row layout); One for Summer (SummerSports.java)

3. 在WinterSports.java 裡判斷所選的運動項目是否包含disciplines:
     If no, 直接顯現events (Eventitem.java + eventlayout.xml)
     If yes, 先到DisciplineItem.java + WinterAdapter.java; 
                再到EventWithDiscipline.java + eventlayout.xml

4. 在SummerSports.java 裡判斷所選的運動項目是否包含disciplines:
     If no, 直接顯現events (SummerEventItem.java + eventlayout.xml)
     If yes, 先到SummerDisciplineItem.java + WinterAdapter.java; 
                再到SummerEventWithDiscipline.java + eventlayout.xml

5. 在 event 的 row 最上方加上 Header (headerlayout.xml)







Cq_SportsTapActivity.java:

public class Cq_SportsTapActivity extends TabActivity {
   
TabHost tabhost;
Intent intent;
Resources res;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tabhost = getTabHost();
        res = getResources();
        
        //Olympic Summer Sport Tab
        intent = new Intent().setClass(this, SummerSports.class);
        tabhost.addTab(tabhost.newTabSpec("summer").setIndicator("Summer", res.getDrawable(R.drawable.sunny02)).setContent(intent));
        
        //Olympic Winter Sport Tab
        Intent intent = new Intent().setClass(this, WinterSports.class);
        tabhost.addTab(tabhost.newTabSpec("winter").setIndicator("Winter", res.getDrawable(R.drawable.snowman02)).setContent(intent));
        
        //Non-Olympic Sports Tab
//        intent = new Intent().setClass(this, NonSports.class);
//        tabhost.addTab(tabhost.newTabSpec("non").setIndicator("Other", res.getDrawable(R.drawable.cloud01)).setContent(intent));
        
        tabhost.setCurrentTab(0);
        
    }
}

***********************************************
main.xml:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
    <LinearLayout 
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">
        
   <!--      
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="運動" 
        android:textSize="30px"
        android:textColor="@color/lime"/> -->
        
        <!-- 定義tab的樣式 -->
        <TabWidget android:id="@android:id/tabs" 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        
        <!-- 定義每個tab裡內容的呈現 -->

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" >
</FrameLayout>
                    
     </LinearLayout>

</TabHost>

********************************************
public class SportsData extends Activity{

String [] wintersportsEng = {"Biathlon", "Bobsleigh", "Curling", "Ice Hockey", "Luge", "Skating", "Skiing"};
String [] wintersportsChi = {"冬季兩項(滑雪射擊)", "連橇", "冰上滾石", "冰上曲棍球", "仰臥滑行雪橇", "滑冰", "滑雪"};
String [] wintersportsRus = {"биатлон", "бобслей", "кёрлинг", "хоккей на льду", "санный спорт", "катание на коньках", "катание на лыжах"};
String [] summersportsEng = {"Aquatics", "Archery", "Athletics", "Badminton","Basketball", "Boxing","Canoe", "Cycling"
"Equestrian", "Fencing", "Football", "Golf", "Gymnastics", "Handball", "Hockey", "Judo", "Modern Pentathlon", "Rowing",
"Rugby", "Sailing", "Shooting", "Table Tennis", "Taekwondo", "Tennis", "Triathlon", "Volleyball", "Weightlifting", "Wrestling"};
String [] summersportsChi = {"水上運動", "射箭", "競技運動", "羽毛球","籃球", "拳擊","獨木舟", "單車"
"騎術", "西洋劍", "足球", "高爾夫球", "體操", "手球", "曲棍球", "柔道", "現代五項", "划船",
"橄欖球", "帆船", "射擊", "桌球", "跆拳", "網球", "三項運動", "排球", "舉重", "摔角"};
String [] summersportsRus = {"водные виды спорта", "стрельба из лука", "лёгкая атлетика", "бадминтон","баскетбол", "бокс","каноэ", "велоспорт"
"конный спорт", "фехтование", "футбол", "гольф", "гимнастика", "гандбол", "хоккей", "дзю-до", "пентатлон; пятиборье", "Академическая гребля",
"регби", "парусный спорт", "стрельба", "настольный теннис; пинг-понг", "тхэквондо", "теннис", "триатлон; троеборье", "волейбол", "тяжёлая атлетика", "борьба; схватка"};
//有disciples的運動項目
String [] winterDisciplines = {"Bobsleigh", "Skating", "Skiing"};
String [] summerDisciplines = {"Aquatics","Canoe","Cycling","Equestrian", "Gymnastics","Volleyball", "Wrestling"};
}

********************************************




WinterSports.java:

public class WinterSports extends ListActivity {

SportsData datahelper;
@Override
public void onCreate(Bundle winter) {
super.onCreate(winter);
    datahelper = new SportsData();
    
    
    ArrayAdapter<String> adapter = new WinterAdapter(this, datahelper.wintersportsEng, datahelper.wintersportsChi, datahelper.wintersportsRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//List Winter sports
String strTested = datahelper.wintersportsEng[position];
int flag = 0;
for (int i=0; i< datahelper.winterDisciplines.length; i++){
if (strTested == datahelper.winterDisciplines[i]){
flag = 1;
}
}
if (flag == 0){
//Toast.makeText(WinterSports.this, datahelper.wintersportsEng[position] + " 沒有細項目!", Toast.LENGTH_SHORT).show();
//List event item (no discipline)
Intent intent = new Intent(WinterSports.this, Eventitem.class);
intent.putExtra("EVENT", datahelper.wintersportsEng[position]);
startActivity(intent);
}else if (flag == 1){
//List discipline items
Intent intent = new Intent(WinterSports.this, DisciplineItem.class);
intent.putExtra("DISCIPLINE", datahelper.wintersportsEng[position]);
startActivity(intent);
//Toast.makeText(WinterSports.this, datahelper.wintersportsEng[position] + " has subitems!", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(WinterSports.this, datahelper.wintersportsEng[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(WinterSports.this, "一共有 "+ Integer.toString(datahelper.wintersportsEng.length)+" 個運動項目", Toast.LENGTH_SHORT).show();
}
});
}

}


************************************************

WinterAdapter:

public class WinterAdapter extends ArrayAdapter<String>{


private final Context context;
private final String []values1;
private final String []values2;
private final String []values3;
public WinterAdapter(Context context, String [] engsport, String []chisport,String [] russport) {
super(context, R.layout.winterlayout, engsport);
// TODO Auto-generated constructor stub
this.context = context;
this.values1 = engsport;
this.values2 = chisport;
this.values3 = russport; 
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = inflater.inflate(R.layout.winterlayout, parent, false);
TextView textviewEng = (TextView)rowview.findViewById(R.id.winterTextViewEng);
TextView textviewChi = (TextView)rowview.findViewById(R.id.winterTextViewChi);
TextView textviewRus = (TextView)rowview.findViewById(R.id.winterTextViewRus);
String s1 = values1[position];
String s2 = values2[position];
String s3 = values3[position];
textviewEng.setText(s1);
textviewChi.setText(s2);
textviewRus.setText(s3);
return rowview;
}
}

********************************************
DisciplineItem.java:

public class DisciplineItem extends ListActivity{

public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getDiscipline;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getDiscipline = extras.getString("DISCIPLINE");
}
Cursor c = getDisciplines(getDiscipline);
c.moveToFirst();
final String [] strEng = new String [c.getCount()];
String [] strChi = new String [c.getCount()];
String [] strRus = new String [c.getCount()];
for (int i=0; i < strEng.length; i++){
strEng [i] = c.getString(0);
strChi [i] = c.getString(1);
strRus [i] = c.getString(2);
c.moveToNext();
}
c.close();
ArrayAdapter <String> adapter = new WinterAdapter(this, strEng, strChi, strRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
//Toast.makeText(DisciplineItem.this, strEng[position], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DisciplineItem.this, EventWithDiscipline.class);
intent.putExtra("EVENT", strEng[position]);
startActivity(intent);
}
});
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getDisciplines(String strSport){
// String table = "events";
// String [] columns = {"discipline", "disciplinechi", "disciplinerus"};
// String selection = "sport=?";
// String [] selectionArgs = new String [] {strSport};
// return db.query(table, columns, selection, selectionArgs, null, null, null);
String sql = "select distinct discipline, disciplinechi, disciplinerus from events where sport='" + strSport + "'";
Cursor c = db.rawQuery(sql, null);
return c;
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}

********************************************
Eventitem.java

public class Eventitem extends ListActivity{

public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getEvent = extras.getString("EVENT");
}
Cursor c = getEvents(getEvent);
c.moveToFirst();
String [] str1 = new String [c.getCount()];
String [] str2 = new String [c.getCount()];
for (int i = 0; i < str1.length; i++){
str1[i] = c.getString(0);
str2[i] = c.getString(1);
c.moveToNext();
}
c.close();
//Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText(getEvent + " :");  //textview1.setText(getEvent + " :  ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(str1.length) + " events");
listview.addHeaderView(header);
 
//Custom adapter: EventAdapter
ArrayAdapter<String> adapter = new EventAdapter(this, str1, str2);
setListAdapter(adapter);
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getEvents(String strSport){
String table = "events";
String [] columns = {"event", "pic"};
String selection = "sport=? AND winter=?";
String [] selectionArgs = new String [] {strSport, "y"};
return db.query(table, columns, selection, selectionArgs, null, null, null);
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}
*************************************************
EventWithDiscipline.java

public class EventWithDiscipline extends ListActivity{
public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getEvent = extras.getString("EVENT");
}
Cursor c = getEvents(getEvent);
c.moveToFirst();
String [] str1 = new String [c.getCount()];
String [] str2 = new String [c.getCount()];
for (int i = 0; i < str1.length; i++){
str1[i] = c.getString(0);
str2[i] = c.getString(1);
c.moveToNext();
}
c.close();
//Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText(getEvent + " :   ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(str1.length) + " events");
listview.addHeaderView(header);
ArrayAdapter<String> adapter = new EventAdapter(this, str1, str2);
setListAdapter(adapter);
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getEvents(String strSport){
String table = "events";
String [] columns = {"event", "pic"};
String selection = "discipline=? AND winter=?";
String [] selectionArgs = new String [] {strSport, "y"};
return db.query(table, columns, selection, selectionArgs, null, null, null);
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}
****************************************************
EventAdapter.java

public class EventAdapter extends ArrayAdapter<String>{

private final Context context;
private final String [] values1;
private final String [] values2;
public EventAdapter(Context context, String [] event, String [] pic) {
super(context, R.layout.eventlayout, event);
// TODO Auto-generated constructor stub
this.context = context;
this.values1 = event;
this.values2 = pic;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = inflater.inflate(R.layout.eventlayout, parent, false);
TextView textview = (TextView)rowview.findViewById(R.id.eventTextView01);
ImageView imageview = (ImageView)rowview.findViewById(R.id.eventImageView01);
String s = values1[position];
textview.setText(s);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/OlymWinter/" + values2[position]);
imageview.setImageBitmap(bMap);
return rowview;
}

}

****************************************************

winterlayout.xml:

<?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="wrap_content" >
<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/winterImageView01"
            android:layout_width="25px"
            android:layout_height="25px"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="10dp"
            android:src="@drawable/flagusa" />
        
        <TextView
                android:id="@+id/winterTextViewEng"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:textColor="@color/white"
                android:textSize="25px" /> <!-- android:textSize="20px" -->
  </LinearLayout>
  
        <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/winterImageView01"
            android:layout_width="25px"
            android:layout_height="25px"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="10dp"
            android:src="@drawable/flagtaiwan" />
        
        <TextView
                android:id="@+id/winterTextViewChi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:textColor="@color/silver"
                android:textSize="25px" />  <!-- android:textSize="20px" -->
  </LinearLayout>
  
            <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/winterImageView01"
            android:layout_width="25px"
            android:layout_height="25px"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="10dp"
            android:src="@drawable/flagrussian" />
        
        <TextView
                android:id="@+id/winterTextViewRus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5px"
                android:text=""
                android:textSize="25px"
                android:textColor="@color/gray"
                 />  <!-- android:textSize="20px" -->
  </LinearLayout>
   
       

  </LinearLayout>          

    <ImageView
        android:id="@+id/winterImageView02"
        android:layout_width="50px"
        android:layout_height="30px"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/arrowright1" />

</RelativeLayout>

***********************************************
SummerSports.java:
public class SummerSports extends ListActivity{

SportsData helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
helper = new SportsData();
ArrayAdapter<String> adapter = new WinterAdapter(this, helper.summersportsEng, helper.summersportsChi, helper.summersportsRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Toast.makeText(SummerSports.this, helper.summersportsEng[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(SummerSports.this,"一共有 " + Integer.toString(helper.summersportsEng.length) + " 個運動項目", Toast.LENGTH_SHORT).show();
String disciplineTested = helper.summersportsEng[position];
int flag = 0;
for (int i = 0; i< helper.summerDisciplines.length; i++ ){
if (helper.summerDisciplines[i] == disciplineTested){
flag = 1;
}
}
if (flag == 0){
//Toast.makeText(SummerSports.this, helper.summersportsEng[position] + " 沒有細項目!", Toast.LENGTH_SHORT).show();
//List event item (no discipline)
Intent intent = new Intent(SummerSports.this, SummerEventItem.class);
intent.putExtra("EVENT", helper.summersportsEng[position]);
startActivity(intent);
}else if (flag == 1){
//List discipline items
Intent intent = new Intent(SummerSports.this, SummerDisciplineItem.class);
intent.putExtra("DISCIPLINE", helper.summersportsEng[position]);
startActivity(intent);
//Toast.makeText(SummerSports.this, helper.summersportsEng[position] + " has subitems!", Toast.LENGTH_SHORT).show();
}
}
});
}

}

****************************************************

SummerDisciplineItem.java:

public class SummerDisciplineItem extends ListActivity{

public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getDiscipline;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getDiscipline = extras.getString("DISCIPLINE");
}
Cursor c = getDisciplines(getDiscipline);
c.moveToFirst();
final String [] strEng = new String [c.getCount()];
String [] strChi = new String [c.getCount()];
String [] strRus = new String [c.getCount()];
for (int i=0; i < strEng.length; i++){
strEng [i] = c.getString(0);
strChi [i] = c.getString(1);
strRus [i] = c.getString(2);
c.moveToNext();
}
c.close();
ArrayAdapter <String> adapter = new WinterAdapter(this, strEng, strChi, strRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
//Toast.makeText(DisciplineItem.this, strEng[position], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SummerDisciplineItem.this, SummerEventWithDiscipline.class);
intent.putExtra("EVENT", strEng[position]);
startActivity(intent);
}
});
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getDisciplines(String strSport){
// String table = "events";
// String [] columns = {"discipline", "disciplinechi", "disciplinerus"};
// String selection = "sport=?";
// String [] selectionArgs = new String [] {strSport};
// return db.query(table, columns, selection, selectionArgs, null, null, null);
String sql = "select distinct discipline, disciplinechi, disciplinerus from events where sport='" + strSport + "'";
Cursor c = db.rawQuery(sql, null);
return c;
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}
******************************************************
SummerEventItem.java:

public class SummerEventItem extends ListActivity{
public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getEvent = extras.getString("EVENT");
}
Cursor c = getEvents(getEvent);
c.moveToFirst();
String [] str1 = new String [c.getCount()];
String [] str2 = new String [c.getCount()];
for (int i = 0; i < str1.length; i++){
str1[i] = c.getString(0);
str2[i] = c.getString(1);
c.moveToNext();
}
c.close();
//Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText(getEvent + " :   ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(str1.length) + " events");
listview.addHeaderView(header);
ArrayAdapter<String> adapter = new EventAdapter(this, str1, str2);
setListAdapter(adapter);
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getEvents(String strSport){
String table = "events";
String [] columns = {"event", "pic"};
String selection = "sport=? AND summer=?";
String [] selectionArgs = new String [] {strSport, "y"};
return db.query(table, columns, selection, selectionArgs, null, null, null);
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}
****************************************************
SummerEventWithDiscipline.java


public class SummerEventWithDiscipline extends ListActivity{

public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getEvent = extras.getString("EVENT");
}
Cursor c = getEvents(getEvent);
c.moveToFirst();
String [] str1 = new String [c.getCount()];
String [] str2 = new String [c.getCount()];
for (int i = 0; i < str1.length; i++){
str1[i] = c.getString(0);
str2[i] = c.getString(1);
c.moveToNext();
}
c.close();
//Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText(getEvent + " :   ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(str1.length) + " events");
listview.addHeaderView(header);
ArrayAdapter<String> adapter = new EventAdapter(this, str1, str2);
setListAdapter(adapter);
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getEvents(String strSport){
String table = "events";
String [] columns = {"event", "pic"};
String selection = "discipline=? AND summer=?";
String [] selectionArgs = new String [] {strSport, "y"};
return db.query(table, columns, selection, selectionArgs, null, null, null);
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}


*********************************************

summerlayout.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/summerTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Summer" />

</LinearLayout>

*************************************************
headlayout.xml

<?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="wrap_content"
     >

          <TextView
            android:id="@+id/headerTextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="1dp"
            android:layout_marginTop="1px"
            android:text="運動" 
            android:textSize = "18dp"
            android:textColor="@color/lime"/> 
            <!-- Tata:
            android:layout_marginRight="1dp"   
            android:layout_marginLeft="15dp"
            green -->

        <TextView
            android:id="@+id/headerTextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="1dp"
            android:layout_marginRight="2px"
            android:layout_marginTop="1px"
            android:layout_toRightOf="@+id/headerTextView01"
            android:text="項目"
            android:textSize = "20dp"
            android:textColor="@color/orange"/>  <!-- green -->


</RelativeLayout>



ListView Example - Olympic Games Sports

ListView Example - Olympic Games Sports


Modified files:


1) 解決在 Header indexed 0 的問題;
2) 精簡java檔;夏季共用冬季的java檔:(可以刪除 SummerDisciplineItem.java,
                                                                         SummerEventItem.java,
                                                                         SummerEventWithDiscipline.java)
3)共用Eventitem.java (精簡化:刪除EventWithDiscipline.java)


WinterSports.java:



public class WinterSports extends ListActivity {

SportsData datahelper;
@Override
public void onCreate(Bundle winter) {
super.onCreate(winter);
    datahelper = new SportsData();
    
    
    //Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText("Winter Olympic: ");  //textview1.setText(getEvent + " :  ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(datahelper.wintersportsEng.length) + " sports");
listview.addHeaderView(header);
    
//Set customized Adapter
    ArrayAdapter<String> adapter = new WinterAdapter(this, datahelper.wintersportsEng, datahelper.wintersportsChi, datahelper.wintersportsRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (position != 0) { //In order to skip the first row index (0) 
ListView listview = getListView();
String strTested = listview.getItemAtPosition(position).toString(); //取得 the selected row item 
// Toast.makeText(getApplicationContext(), strTested,
// Toast.LENGTH_SHORT).show();

int flag = 0;
for (int i = 0; i < datahelper.winterDisciplines.length; i++) { //to compare with data for discipline check
if (strTested == datahelper.winterDisciplines[i]) {
flag = 1;
}
}
if (flag == 0) { //sport with no disciplines
Intent intent = new Intent(WinterSports.this,Eventitem.class);
intent.putExtra("EVENT",strTested);
intent.putExtra("SEASON", "winter")
intent.putExtra("SportOrDiscipline", "sport");//
startActivity(intent);

} else if (flag == 1) { // sport with disciplies
// List discipline items
Intent intent = new Intent(WinterSports.this,DisciplineItem.class);
intent.putExtra("DISCIPLINE",strTested);
intent.putExtra("SEASON", "winter");
startActivity(intent);
}

}
   
}
});
}
}

*****************************************************
SummerSports.java


public class SummerSports extends ListActivity{

SportsData helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
helper = new SportsData();
//Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText("Summer Olympic: ");  //textview1.setText(getEvent + " :  ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(helper.summersportsEng.length) + " sports");
listview.addHeaderView(header);
ArrayAdapter<String> adapter = new WinterAdapter(this, helper.summersportsEng, helper.summersportsChi, helper.summersportsRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (position != 0) {
ListView listview = getListView();
String disciplineTested = listview.getItemAtPosition(position).toString();
int flag = 0;
for (int i = 0; i< helper.summerDisciplines.length; i++ ){
if (helper.summerDisciplines[i] == disciplineTested){
flag = 1;
}
}
if (flag == 0){
Intent intent = new Intent(SummerSports.this, Eventitem.class);
intent.putExtra("EVENT", disciplineTested);
intent.putExtra("SEASON", "summer");
intent.putExtra("SportOrDiscipline", "sport");

startActivity(intent);
}else if (flag == 1){
//List discipline items
Intent intent = new Intent(SummerSports.this, DisciplineItem.class);
intent.putExtra("DISCIPLINE", disciplineTested);
intent.putExtra("SEASON", "summer");
startActivity(intent);
//Toast.makeText(SummerSports.this, helper.summersportsEng[position] + " has subitems!", Toast.LENGTH_SHORT).show();
}
}
}
});
}

}

********************************************
DisciplineItem.java

public class DisciplineItem extends ListActivity{

public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getDiscipline;
String season;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getDiscipline = extras.getString("DISCIPLINE");
season = extras.getString("SEASON");
}
Cursor c = getDisciplines(getDiscipline);
c.moveToFirst();
final String [] strEng = new String [c.getCount()];
String [] strChi = new String [c.getCount()];
String [] strRus = new String [c.getCount()];
for (int i=0; i < strEng.length; i++){
strEng [i] = c.getString(0);
strChi [i] = c.getString(1);
strRus [i] = c.getString(2);
c.moveToNext();
}
c.close();
ArrayAdapter <String> adapter = new WinterAdapter(this, strEng, strChi, strRus);
setListAdapter(adapter);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
//Toast.makeText(DisciplineItem.this, strEng[position], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DisciplineItem.this, EventWithDiscipline.class);
intent.putExtra("EVENT", strEng[position]);
intent.putExtra("SEASON", season);
intent.putExtra("SportOrDiscipline", "discipline");

startActivity(intent);
}
});
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getDisciplines(String strSport){
// String table = "events";
// String [] columns = {"discipline", "disciplinechi", "disciplinerus"};
// String selection = "sport=?";
// String [] selectionArgs = new String [] {strSport};
// return db.query(table, columns, selection, selectionArgs, null, null, null);
String sql = "select distinct discipline, disciplinechi, disciplinerus from events where sport='" + strSport + "'";
Cursor c = db.rawQuery(sql, null);
return c;
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}



********************************************
Eventitem.java



public class Eventitem extends ListActivity{

public static final String PATH = "/databases";
private final String DATABASE_FILENAME = "yundon.sqlite";
DBConnection dbHelper;
SQLiteDatabase db = openDatabase();
String getEvent;
String getSeason;
String getSportOrDiscipline;


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
getEvent = extras.getString("EVENT");
getSeason = extras.getString("SEASON");
getSportOrDiscipline = extras.getString("SportOrDiscipline");

}
Cursor c = getEvents(
getEvent, getSportOrDiscipline, getSeason);

c.moveToFirst();
String [] str1 = new String [c.getCount()];
String [] str2 = new String [c.getCount()];
for (int i = 0; i < str1.length; i++){
str1[i] = c.getString(0);
str2[i] = c.getString(1);
c.moveToNext();
}
c.close();
//Header
ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText(getEvent + " :");  //textview1.setText(getEvent + " :  ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(str1.length) + " events");
listview.addHeaderView(header);
 
//Custom adapter: EventAdapter
ArrayAdapter<String> adapter = new EventAdapter(this, str1, str2);
setListAdapter(adapter);
}

public static class DBConnection extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "yundon.sqlite";
private static final int DATABASE_VERSION = 1;
final SQLiteDatabase db;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
db = this.getReadableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public Cursor getEvents(String strSport, String season){
String table = "events";
String [] columns = {"event", "pic"};
String selection = sportOrDiscipline + "=? AND " + season + "=?";
//原來String selection = "sport=? AND winter=?";
String [] selectionArgs = new String [] {strSport, "y"};
return db.query(table, columns, selection, selectionArgs, null, null, null);
}
public SQLiteDatabase openDatabase(){
try {
final String DATABASE_PATH = "/mnt/sdcard/databases";
final String PATH = "/databases";
File myDataPath = new File (DATABASE_PATH + PATH);
String databaseFilename = myDataPath + "/" + DATABASE_FILENAME;
if (!myDataPath.exists()){
myDataPath.mkdirs();
}
if (!(new File(databaseFilename)).exists()){
InputStream is = getResources().openRawResource(R.raw.yundon);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte [] buffer = new byte [8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openDatabase(databaseFilename, null, RESULT_OK);
return database;
}catch (Exception e){
Log.i("DB", "DB_DIR_EXCEPTION: ");
}
return null;
}
}

************************************************



2012年3月12日 星期一

String to Drawable


String 轉 drawable:

e.g. 1


private void displayImage() {

String uri = "drawable/imagefile01"; 
 // int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(uri, null, getPackageName()); 
ImageView imageView = (ImageView) findViewById(R.id.myImageView); 
Drawable image = getResources().getDrawable(imageResource); imageView.setImageDrawable(image);
 }

***********************************************

e.g.2 應用在 database + ListAdapter
假設圖檔放在 res/drawable/ 下,其檔名則是以字串方式存在 database 裡。可以下列方式將之顯現出來:



Cursor c = getData();
c.moveToFirst();

String [] imgStrings = new String [c.getCount()]; //將存放從db來的圖檔名
int [] imgResources = new int [c.getCount()];//準備將字串轉成整數格式 
Object [] imgObj = new Object [c.getCount()];//準備接收成 Drawable 的物件

for (int i = 0; i < str1.length; i++){
  imgStrings [i] = c.getString(0);//圖形檔名後接有 .png
 //將存在db的圖檔字串檔名轉成drawable
 String uri = "drawable/" + str2[i].substring(0, str2[i].length()-4).toString(); 
 // 刪掉後頭的 .png (四個位元)
 imgResources[i] = getResources().getIdentifier(uri, null, getPackageName());
 imgObj [i] = getResources().getDrawable(imgResources[i]);
c.moveToNext();
}
c.close(); 
/CustomAdapter. 將得到的drawable 物件陣列,傳入自己設定的adapter 
ArrayAdapter<String> adapter = new CustomAdapter(this, imgObj); 
setListAdapter(adapter);


&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


CustomAdapter.java 自己設定的 Adapter:

public class CustomAdapter extends ArrayAdapter<String>{

 private LayoutInflater inflater;
 private final Context context;

private final Object [] img; //來接收傳進來的drawable 物件陣列

public EventAdapter(Context context, Object [] imgObj) { //Constructor
 super(context, R.layout.eventlayout, event);
 this.context = context; 
 this.img = imgObj;
}
@Override

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

   ViewHolder holder = new ViewHolder(); 
   inflater = LayoutInflater.from(context); 
   View rowview = inflater.inflate(R.layout.eventlayout, parent, false);
   holder.imageview = (ImageView)rowview.findViewById(R.id.ImageView01); 
   Object drawable = img[position]; //將Object 型態轉為 Drawable
   holder.imageview.setImageDrawable((Drawable) drawable);
   return rowview;
   } 

    static class ViewHolder
    ImageView imageview;
    }

}

2012年3月11日 星期日

去字串的字元

如果刪除字串的某些字元:



設定某一字串:
String aStr = love;

str = aStr.substring(0, str.length()-0).toString(); // ==> love
str = aStr.substring(0, str.length()-1).toString(); // ==> lov
str = aStr.substring(0, str.length()-2).toString(); // ==> lo
str = aStr.substring(0, str.length()-3).toString(); // ==> l

OR   
str = aStr.substring(0, 1).toString();//l
str = aStr.substring(0, 2).toString();//lo
str = aStr.substring(0, 3).toString();//lov
str = aStr.substring(0, 4).toString();//love



只要取 "crazy" (紅色的部分─12個字元不要):
String aStr = "irrevocably-crazy";

str = aStr.substring(12, aStr.length());   第一個參數是從第幾個字元開始;第二個參數是到哪個字元結束


如果
aStr = "love." 為了要去掉最後的句點  str = aStr.substring (0, aStr.length()-1).toString();