简体   繁体   中英

android. Send data from class to activity and get result

I have Activity1 with expandable list view, which has custom adapter,

In that adapter class, i capture onClick event of button within child items of my expandable list view, and i need to pass data about selected child item of expandable list to Activity2 where user does some choises and i need to get result when it's done, ( when Activity2 is finished ) in adapter class, how it can be realized?

Working in adapter class, i can start Activity2 only in new thread, so i can't call some StartActivityForResult ...

I hope there is some ways like creating shared variable and using it in anywhere, but don't know how.. so help me please!

You can create OnClickListener class init it in activity and pass to the adapter. Set it to the buttons in your adapter. After click on a button his listener will fire and do whatever you want. If you need to pass some params simply override OnClickListener to get all the params you need.

You can write onClickListener like this (example for ListActivity , so just change getListView to your ListView ):

private OnClickListener mEditClickListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        int position = getListView().getPositionForView(v);
    }
}

In the adapter constructor, take the Context as parameter and save it in class variable. For example it is saved in Context callerContext variable. Now, in onItemClickListener, write following code

Intent i = new Intent( callerContext , Activity2.class );
i.putExtra( "value" , items[position] );
callerContext.startActivity( i );

在按钮上单击set startActivityForResult和从Activity2设置结果,这将在Activity1的onActivityResult中自动找到。

If you want the result back from the activity to your normal class, supposed it is a class with a custom adapter within it.

  1. you cannot use startActivityForResult because you are not in an activity
  2. what I did is that i launched the activity from the class with an intent. Then I calculated or did what I have to. From this activity I send the information to the main class supposed with a method MainActivity.the_method() and in the main activity I changed the custom adapter o did what I have to using the adapter object and calling adapter.getItem(position)

Hope this can give you an idea

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM