如何将活动中的数据发送到其父片段?

时间:2016-03-05 10:06:12

标签: android listview android-fragments android-intent android-activity

我有一个主要活动,里面有一个带有图像视图的片段。单击此图像视图时,将启动包含列表视图的新活动。我想返回用户点击此列表视图的位置(索引),返回到片段。

片段代码

package com.example.kedee.testgradle;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 */
public class ASKFragment extends Fragment implements View.OnClickListener{
    private Context context;
    private View rootView;
    private int pos;

    public ASKFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView= inflater.inflate(R.layout.fragment_ask, container, false);
        context=inflater.getContext();
        setListeners();
        return  rootView;
    }

    void setListeners(){
        ImageView catIcon=(ImageView)rootView.findViewById(R.id.cat_icon);
        catIcon.setOnClickListener(this);



    }

    @Override
    public void onClick(View v) {
        int vID=v.getId();
        if(vID==R.id.cat_icon){
            Intent intent=new Intent(getActivity(),ASK.class);
            getActivity().startActivity(intent);
        }

    }
}    

从此片段调用的活动代码。 (ASK活动)

package com.example.kedee.testgradle;

import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ASK extends AppCompatActivity {
    private int index;
    private String[] catNames= {"Acad","Emer","Tech","Exam","Station","Finance","Medical","Place","Sports" ,
            "Others" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask);
        ListView listView=(ListView)findViewById(R.id.ask_cat_listView);
        listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,catNames));
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> listView, View v, int pos, long id){
                index=pos;
                //code to return back this index to the parent fragment?
            }
        });
    }


}

3 个答案:

答案 0 :(得分:4)

使用startActivityForResult

<强> 1。在ASKFragment

Intent intent=new Intent(getActivity(),ASK.class);
getActivity().startActivityForResult(intent, 22 /* any other request code you want */);

<强> 2。有目的地通过职位。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> listView, View v, int pos, long id){
                index=pos;
                Intent i = new Intent();
                i.putExtra("position", index);
                setResult(RESULT_OK, i);
                finish();
            }
        });

第3。您要添加或替换片段的活动。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 22 && resultCode == RESULT_OK) {
            // get the position from intent
            if(data.getExtras()!=null && data.hasExtra("position")){
               int position = data.getExtras().getInt("position");
               // pass this position to fragment.
            }
        }
    }

修改
将值从“活动”发送到片段。
1)在片段中创建函数

public void getPositionOfList(int position){
   // here is the position
}

2)来自调用片段方法的Activity。

if (requestCode == 22 && resultCode == RESULT_OK) {
                // get the position from intent
                if(data.getExtras()!=null && data.hasExtra("position")){
                   int position = data.getExtras().getInt("position");
                   // pass this position to fragment.
                   ((ASKFragment)fragmentManager.findFragmentById(/*id of your container*/)).getPositionOfList(position);
                }
            }

答案 1 :(得分:0)

您可以通过调用/启动具有listview

的新活动来实现此目的
  

将startActivity替换为startActivityForResult

并进一步将任何数据发送回调用活动。然后,使用onActivityResult处理它。

答案 2 :(得分:0)

您必须使用如下的OnActivityResult

在主要活动中你有片段,你必须这样写

  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.viewpager);
    fragment.onActivityResult(requestCode, resultCode, data);
}

然后在你想要结果的片段中,你必须写下面的内容

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {


    if(resultCode == getActivity().RESULT_OK) {

        switch(requestCode) {

            case REQUEST_PICK_FILE:

                if(data.hasExtra(FilePicker.EXTRA_FILE_PATH)) {

                    selectedFile = new File
                            (data.getStringExtra(FilePicker.EXTRA_FILE_PATH));
                    tvFile.setText(selectedFile.getPath());

                }
                break;
        }
    }
}

您必须将此代码放在要打开的活动

        Intent intent = new Intent(getActivity(), FilePicker.class);
    startActivityForResult(intent, REQUEST_PICK_FILE);