My main activity page for the android app is mainly a listView and on clicking an item in that list I would like a new activity to start. I have created the intent and such as follows in the onCreate method of my MainActivity class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(adapter);
final MainActivity context = this;
lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent myIntent = new Intent(context, SubActivity.class);
myIntent.addFlags(position); //Optional parameters
context.startActivity(myIntent);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My new activity class looks like this:
public class SubActivity extends MainActivity{
ArrayList<String> sublist = new ArrayList<String>();
ArrayAdapter<String> subadapter;
ArrayList<ArrayList<String>> corrReceipts;
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
int position = intent.getFlags(); //this gives me the index of the receipt
corrReceipts = super.addedReceipts;
TextView tv = new TextView(this);
tv.setText("Hello");
subadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sublist);
ListView slv = (ListView) findViewById(R.id.sublistview);
slv.setAdapter(subadapter);
sublist.addAll(corrReceipts.get(position));
subadapter.notifyDataSetChanged();
setContentView(slv);
}
}
I have my subActivity class extending MainActivity because it needs to access an array from which to get the information from. When I run this code, and click a list item, nothing happens. Any help as to what I'm doing wrong would be of great help!
All you want is an ItemClickListener
not an ItemSelectedListener
.
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent myIntent = new Intent(context, SubActivity.class);
myIntent.addFlags(position); //Optional parameters
context.startActivity(myIntent);
}
});
OnItemSelectedListener
is used for Spinners, and OnItemClickListener
is used for ListViews.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.