Reputation: 113
I'm relativly new in the world of Android programming and I ran into some trouble. The problem is that I have defined a gridview in my MainActivity which consists of several imageViews. Those ImageViews have an onClicklistener which opens another Activity with another gridView. When selecting an element (image) in this grid I want to update the gridview in my MainActivity to adopt the selected Element but actually i have no Idea how to implement this.
I found the following code to update the gridView which is working if I try to update my Grid in the same Activity:
adapter.notifyDataChanged();
grid.invalidateViews();
grid.setAdapter(adapter);
The onClickListener in my second Activity:
mGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ResolveInfo info = mApps.get(position);
//sets the new drawable
Helper.selectedAppImages[0]=getResources().getDrawable(R.drawable.ic_launcher);
//UPDATE THE GRIDVIEW IN MY MAINACTIVITY
AppView.this.finish() ;
}
});
Upvotes: 1
Views: 751
Reputation: 17401
Second activity:
mGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ResolveInfo info = mApps.get(position);
//sets the new drawable
Helper.selectedAppImages[0]=getResources().getDrawable(R.drawable.ic_launcher);
//UPDATE THE GRIDVIEW IN MY MAINACTIVITY
Intent returnIntent = new Intent();
returnIntent.putExtra("info",info);//<-- or set the image that you want to change
AppView.this.setResult(RESULT_OK,returnIntent);
AppView.this.finish() ;
}
});
Start second activity as:
startActivityForResult(intent,1);
And in main activity override following function:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("info");
adapter.notifyDataChanged();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
Upvotes: 0
Reputation: 906
In your MainActivity use startActivityForResult
to display the second Activity passing down data which you need in your second Activity and also override in your MainActivity onActivityResult
. When selecting an image from your second Activity use setResult(RESULT_OK, data)
followed by finish()
. You'll get the result code and data Intent
in the MainActivity onActivityResult
.
You can take a look here for more info : http://developer.android.com/training/basics/intents/result.html
Upvotes: 1