如何在没有按钮点击事件的情况下将数据从一个片段发送到另一个片段?

时间:2017-10-15 23:36:03

标签: android fragment

我正在用碎片做一些测试来研究它。我有一个疑问。

我有一个主要活动,工具栏只有一个项目,当点击这个项目时,我添加了一个包含列表视图的片段A.

然后我单击列表视图中的一个项目,删除片段A并将其片段B替换为片段A.片段B具有文本视图以显示片段A上单击项目的文本。

要将片段A中列表视图上单击的项目的数据传递到片段BI的textview,还需要在片段B xml上添加一个按钮,当单击此按钮时,单击的项目的数据为发送到片段B并使用正确的单击项目文本更新textview。

但它不可能自动执行此操作?如果在addText(String text)方法上调用此方法“sendDataToFragmentB(View view)”它出现NullPointerException in FragmentB.addText(java.lang.String)。但是,如果我在片段xml中使用onClick =" sendDataTofragmentB"单击按钮时,它可以正常工作。

接口

public interface Listener {
    public void addText(String text);
}

主要活动

public class MainActivity extends AppCompatActivity implements Listener {

    Toolbar toolbar;
    FragmentManager manager;
    private String text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        manager = getFragmentManager();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setTitle("Pets");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String msg = "";

        if (item.getItemId() == R.id.search) {
                msg = "search";
                AddFragmentA();
        }
        Toast.makeText(this, msg + "clicked !", Toast.LENGTH_SHORT).show();
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void addText(String text) {
        this.text = text;

        Toast.makeText(this, "Text Received in Activity" + text, Toast.LENGTH_SHORT).show();
        sendDataToFragmentB();
    }
    public void sendDataToFragmentB(View view) {

            FragmentB fragmentB = (FragmentB) manager.findFragmentByTag("fragB");
            fragmentB.addText(text);

    }
}

片段A:

public class FragmentA extends Fragment {
    private static final String TAG = FragmentA.class.getSimpleName();
    private ListView listItems;

    private String[] items = {
            "item1",
            "item2",
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, container, false);
        listItems = (ListView) view.findViewById(R.id.listviewInFragment);

        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getActivity().getApplicationContext(),
                        android.R.layout.simple_list_item_1, android.R.id.text1, items);
        listItems.setAdapter(adapter);

        listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int positionCode = i;
                String clickedValue = (String) adapterView.getItemAtPosition(i);

                Listener listener = (Listener) getActivity();
                listener.addText(clickedValue);

                Toast.makeText(getActivity().getApplicationContext(), clickedValue, Toast.LENGTH_SHORT).show();
                removeFragmentA();
                AddFragmentB();
            }

        });

        return view;
    }

    public void removeFragmentA(){
        FragmentA fragmentA = (FragmentA) getFragmentManager().findFragmentByTag("fragA");
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        if(fragmentA !=null){
            transaction.remove(fragmentA);
            transaction.commit();
        }
        else{
            Toast.makeText(this.getActivity(), "Fragment A not found", Toast.LENGTH_SHORT).show();
        }
    }
    public void AddFragmentB(){

        FragmentB fragmentB = new FragmentB();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.add(R.id.container, fragmentB, "fragB");
        transaction.commit();
    }
}

片段B:

public class FragmentB extends Fragment {
    private TextView txvResult;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_b, container, false);
        txvResult = (TextView) view.findViewById(R.id.txvResult);
        return view;
    }
    public void addText(String text){
        String result = text;
        txvResult.setText(result);
    }
}

2 个答案:

答案 0 :(得分:0)

简短回答:您想使用Bundles。你可以试试这样的东西

public void AddFragmentB(String clickedText){


    FragmentB fragmentB = new FragmentB();

    Bundle bundle = new Bundle();
    bundle.putString(R.string.clicked_text_key, clickedText);
    fragmentB.setArguments(bundle);

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragmentB, "fragB");
    transaction.commit();
}

FragmentB

@Nullable  
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_b, container, false);
    txvResult = (TextView) view.findViewById(R.id.txvResult);

    addText();

    return view;
}
public void addText(){
    String result = getArguments().getString(R.string.clicked_text_key);
    txvResult.setText(result);
}

请参阅:How to transfer some data to another Fragment?

答案 1 :(得分:0)

您可以在EventBus Sticky Event中尝试使用StickyEvent。单击项目时,只需发布​​像

这样的粘性事件
EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));

然后在添加FragmentB后,您可以使用subscribe方法接收活动。