String [] country = new String[]......
代替从xml收集项目。
String[] imgManager = getResources().getStringArray(R.array.banner);
以编程方式替换硬编码的字符串代码。
public class MainActivity extends ActionBarActivity {
String[] country = new String[] {
"micromax",
"samsung",
"nokia",
"xolo",
"lenovo",
"sony",
"htc",
"lg",
"lava",
"ericsson"
};
public boolean[] status = {
true,
false,
false,
false,
false,
false,
false,
false,
false,
false
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState!=null){
status = savedInstanceState.getBooleanArray("status");
}
ListView lvCountries = (ListView) findViewById(R.id.lv_countries);
OnItemClickListener itemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> lv, View item, int position, long id) {
// TODO Auto-generated method stub
ListView lview = (ListView) lv;
SimpleAdapter adapter = (SimpleAdapter) lview.getAdapter();
HashMap<String,Object> hm = (HashMap) adapter.getItem(position);
RelativeLayout rLayout = (RelativeLayout) item;
ToggleButton tgl = (ToggleButton) rLayout.getChildAt(1);
String strStatus = "";
if(tgl.isChecked()){
tgl.setChecked(false);
strStatus = "Off";
status[position]=false;
}else{
tgl.setChecked(true);
strStatus = "On";
status[position]=true;
}
Toast.makeText(getBaseContext(), (String) hm.get("txt") + " : " + strStatus, Toast.LENGTH_SHORT).show();
}
};
lvCountries.setOnItemClickListener(itemClickListener);
List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>();
for(int i=0;i<10;i++){
HashMap<String, Object> hm = new HashMap<String,Object>();
hm.put("txt", country[i]);
hm.put("stat",status[i]);
aList.add(hm);
}
String[] from = {"txt","stat" };
int[] to = { R.id.tv_item, R.id.tgl_status};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.lv_layout, from, to);
lvCountries.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}