Android Development: Passing information
Im really confused when tr开发者_如何学Cying to do this:
Lets say i want to build a app which allow you to read information about animals.
on my main class i have a listview which items: Cat, Dog, Snake, Rabbit and so on.
If i tap example Dog my other class and my other layout.xml will pop up. In this details.xml layout got a Header text, a picture and a maintext.
However the text is just null or nothing. So how do i do so the text will change depend on which item i clicked.
For Example i dont want text about cat and a cat picture when o pressed the Rabbit item.
Is this possible? Ive tried to call methods but i just get a FC if the method is not in the current class. ive also tried the intent extra but that try didnt went well.
thank you! Your Friend ;D
If i tap example Dog my other class and my other layout.xml will pop up
I guess you have implemented the onListItemClick
protected void onListItemClick(ListView l, View v, int position, long id)
This method has an id
that you can add in the intent to send to the next activity to know which row (so which item) has been clicked.
So in the next activity, you get the right layout.xml
and information depending on the id
received.
Edit
Let's say MyFirstActivity
is your list activity:
public class MyFirstActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[] {"Hello","World","Foo","Bar"}));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this,MySecondActivity.class);
intent.putExtra("id",id);
startActivity(intent);
}
}
Then, in onListItemClick
, it sends an intent to MySecondActivity
with the id
as extra where I can retrieve it and get the info according to it
public class MySecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Long lngId = getIntent().getExtras().getLong("id");
Integer id = lngId.intValue();
String message = null;
switch(id) {
case 0:
message = "Hello";
break;
case 1:
message = "World";
break;
case 2:
message = "Foo";
break;
case 3:
message = "Bar";
break;
}
Toast.makeText(this,message + " was clicked",Toast.LENGTH_SHORT).show();
}
}
Hope this helps
精彩评论