2012年2月27日 星期一

Customized ListView Adapter -- 自定 ListView Adapter



如果能自訂自己喜歡的ListView樣式,如下圖一樣,那一定是很不錯的感覺:



要達到上圖的效果,基本上只要做三件事,便大功完成:
  1、建立自己的adapter(MyCustomListViewAdapter.java)來連接(2)的xml;
  2、建立自己喜歡的單欄樣版(rowlayout.xml):
  3、在主程式上(Cq_MyListViewExampleActivity),將 main.xml 裡的 listview1 連接上自己製作的 adapter.
                                                     全部需要準備的檔如下:



(一)建立自已的adapter:
MyCustomListViewAdapter.java:

package com.cq.listview.example;

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


public
 class
 MyCustomListViewAdapter extends ArrayAdapter<String>{

private final Context context;
private final CharSequence[] values1; //建立兩個參數陣列來接收主程式傳進來的兩個陣列
private final CharSequence [] values2;

   //建構子
   public MyCustomListViewAdapter(Context context, String [] strValues1, String [] strValues2) {
           super(context, android.R.layout.simple_list_item_1, values1);
          // TODO Auto-generated constructor stub
             this.context = context;
             this.values1 = strValues1;
             this.values2 = strValues2;
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      // TODO Auto-generated method stub
          //取得.xml layout檔的資源,用來放入自設的欄位樣式( rowview)
          LayoutInflater inflater =
              (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             
          View rowview = inflater.inflate(R.layout.exampleLayout, parent, false);

          TextView textview = 
                 (TextView)rowview.findViewById(R.id.textview01);  //連接上自設的樣式元素
          ImageView subtopicImageView = 
                (ImageView)rowview.findViewById(R.id.imageview01);

          String s1 = values1[position].toString(); //依次傳入值
          String s2 = strValues2[position].toString();

           //交錯圖檔
          if ((position + 2)%2 == 0){
                   imageview01.setImageResource(R.drawable.basketball);
                   }else if ((position + 2)%2 == 1){
                   imageview01.setImageResource(R.drawable.americanfootball);
                   }
         
           //將傳入的值顯示在textview上
           textview.setText(s1 + "  " + s2);

           return rowview; //傳出單一整個欄位的設置
           }

}

*********************************************
(二)、建立自己喜歡的單欄樣版:

照自己喜歡的方式,準備自定的樣式layout給自定的 listview 用 (如下: rowlayout.xml)。
請準備兩個圖檔(.png),例如basketball.png, tennisball.png
rowlayout.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" >

    <ImageView
        android:id="@+id/imageview01"
        android:layout_width="30px"
        android:layout_height="30px"
        android:layout_marginLeft="4px"
        android:layout_marginRight="10px"
        android:layout_marginTop="4px"
        android:src="@drawable/americanfootball" >
    </ImageView>

    <TextView
        android:id="@+id/textview01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textColor="@color/orange"
        android:textSize="20px" >
    </TextView>

</LinearLayout>


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

(三)、在主程式上,將 main.xml 裡的 listview 連接上自己製作的 adapter.
MainActivity.java (Cq_MyListViewExampleActivity)有兩個自定的String 陣列
(String [] firstStringArray, String [] secondStringArray)的參數,
將用來傳入以下的自設ListView Adapter:



package com.cq.listview.example;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class Cq_MyListViewExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //建立兩個字串陣列
        String [] firstStringArray = {"蘋果", "香吉士", "奇異果", "西洋梨", "西瓜", "哈密瓜"
                                                   "葡萄", "杏子", "琵琶", "甘蔗"};
        String [] secondStringArray = {"apples", "oranges", "kiwi", "pears", "watermelon"
                                                      "cantaloupe", "grapes", "apricots", "loquats", "sugar cane" };
        
        //設ListView參數用以連結.xml的listview
        ListView listview = (ListView)findViewById(R.id.listView1);

        //自設的接口
        MyCustomListViewAdapter adapter = new MyCustomListViewAdapter(this
                             firstStringArray, secondStringArray);

        //將接口連接到ListView的參數
        listview.setAdapter(adapter);
    }
}


***********************************************************************
  附上 main.xml 檔的內容:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="ListView Example 3" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>



2012年2月21日 星期二

android -- string

Int --> String

/* 如何將一整數(4)轉為字串("4")*/

int anInteger = 4; //設一整數變數

//有三種方式
String integerValueToString = Integer.toString(anInteger);//Ans:4
String valueOfIntegerInString = String.valueOf(anInteger);//Ans:4
String stringValue = new String("" + anInteger);//Ans:4

String string = String.format("I have %d children", 5);



2012年2月18日 星期六

ExpandableListActivity_02


Main.java:


public class Cq_ExpandableListActivityActivity extends ExpandableListActivity {
    /** Called when the activity is first created. */
public String [] tourism = {"ARRIVAL", "CITY", "SOCIABLE", "ENTERTAINMENT", "HOTEL", "MEDICAL TREATMENT"};
public String [] tourism1 = {"抵達", "城市", "社交", "娛樂", "旅館", "醫療"};
public String [] arrival = {"customs", "passport"};
public String [] city = {"general", "transport", "taxi"};
public String [] sociable = {"personal", "profession", "meeting", "language"};
public String [] entertainment = {"leisure", "theaters", "exhibition", "sports"};
public String [] hotel = {"general", "check-in", "staying", "check-out"};
public String [] medical = {"general", "surgeons", "dentist", "pharmacy"};
 
 
ExpandableListAdapter mAdapter;
Context mContext;
private String [] groups = tourism1;
private String [][] children = {arrival, city, sociable, entertainment, hotel, medical};
 
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        //Set up our adapter
        mAdapter = new MyExpandableListAdapter (this);
        setListAdapter(mAdapter);
        registerForContextMenu(getExpandableListView());
    }

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
//super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("LittleTa");
menu.add(0,0,0,R.string.hello);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo)item.getMenuInfo();
String title = ((TextView)info.targetView).getText().toString();
int type = ExpandableListView.getPackedPositionType(info.packedPosition);
if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
Toast.makeText(this, title + ":Child" + childPos + " clicked in group " + groupPos, Toast.LENGTH_SHORT).show();
return true;
}else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP){
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
Toast.makeText(this, title+ ":Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
    
public class MyExpandableListAdapter extends BaseExpandableListAdapter{

public MyExpandableListAdapter(Context context){
mContext = context;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return children[groupPosition][childPosition];
}

@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
//Create a Linear Layout for the GroupView
public LinearLayout getGenericView (String string){
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,64);
LinearLayout linearlayout = new LinearLayout (mContext);
ImageView icon = new ImageView (mContext);
    icon.setImageResource(R.drawable.basketball);
    icon.setPadding(45, 0, 0, 0);
    linearlayout.addView(icon);
   
    TextView textview = new TextView (mContext);
    //Center the text vertically
    textview.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    //Set the text starting point
    textview.setPadding(36, 0, 0, 0);
    linearlayout.setLayoutParams(lp);
    linearlayout.addView(textview);
    textview.setText(string);
   
    return linearlayout;
}

@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// String myText = this.getChild(groupPosition,childPosition).toString();
// LinearLayout linearlayout = getGenericView(myText + "QQTATA");
// textview.setText(getChild(groupPosition, childPosition)).toString());
// return linearlayout;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.album_row, null);
TextView textview = (TextView)v.findViewById(R.id.text1);
String myText = this.getChild(groupPosition, childPosition).toString();
textview.setText(myText);
CheckBox cBox = (CheckBox)v.findViewById(R.id.checkbox);
cBox.setVisibility(View.VISIBLE);
ImageView image = (ImageView)v.findViewById(R.id.rowicon);
image.setImageResource(R.drawable.monkey32);
textview.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(Cq_ExpandableListActivityActivity.this, IntentShowMsg.class);
startActivity(intent);
}
});
return v;
}

@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return children[groupPosition].length;
}

@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groups[groupPosition];
}

@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return groups.length;
}

@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String myText = this.getGroup(groupPosition).toString();
return getGenericView(myText);
}

@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
    
    
}

****************************************************
res/layout/album_row.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="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
    android:paddingRight="?android:attr/scrollbarSize"
    android:layout_weight="1" >
    
    <ImageView android:id="@+id/rowicon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="6dip" />
    <TextView android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <CheckBox android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="2dip"
        android:focusable="true"
        android:clickable="true"
        android:gravity="center_vertical"
        android:duplicateParentState="true"
        android:visibility="visible"
        android:text="myText"/>
</LinearLayout>

********************************************
public class IntentShowMsg extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("QQ LOVES TATA.");
tv.setTextColor(Color.YELLOW);
tv.setTextSize(50);
setContentView(tv);
}

}