package com.example.selfdefinelayout;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.*;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(ll);
tv = new TextView(this);
tv.setText("歡迎光臨");
lv = new ListView(this);
String[] str = {"1號房","2號房","3號房","4號房","5號房","6號房"};
//MyAdapter是自訂的視圖,會根據ArrayAdapter來做修改
MyAdapter ad = new MyAdapter(this,android.R.layout.simple_list_item_1,str);
lv.setAdapter(ad);
ll.addView(tv);
ll.addView(lv);
lv.setOnItemClickListener(new ClickListener());
}
class ClickListener implements OnItemClickListener{
public void onItemClick(AdapterView<?> parent, View v, int pos, long id){
TextView tmp = (TextView) v;
tv.setText(tmp.getText());
}
}
class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context cn, int textViewResourceId, String[] objects){
//從ArrayAdapter調用構造函數
super(cn, textViewResourceId, objects);
}
public View getView(int pos, View convView, ViewGroup parent){
ListView l = (ListView) parent;
String s = "------"+ l.getItemAtPosition(pos);
TextView t = new TextView(getBaseContext());
t.setText(pos+s);
t.setTextSize(20);
if(pos % 2 == 0){
t.setBackgroundColor(Color.WHITE);
}else{
t.setBackgroundColor(Color.BLACK);
}
convView = t;
return convView;
}
}
@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;
}
}
留言列表