互动片段

时间:2016-01-28 14:15:13

标签: android android-fragments

我有1个活动和2个片段。在抽屉菜单中,我有两个项目:Fragment1和Fragment2。在fragment1中我有editText和按钮。当我点击按钮时 - 字段中的文本必须记录在第二个片段的listView中。 请帮助我,我怎么能做到这一点。

更改了代码,但是当我点击按钮时,应用程序已停止。 请帮帮我。

MainActivity

public class MainActivity extends AppCompatActivity implements ScreenOne.OnFragmentInteractionListener {

Drawer drawerResult;
ArrayList<String> arrayItems;


String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    PrimaryDrawerItem item1 = new PrimaryDrawerItem()
            .withName(R.string.navigation_menu_item1)
            .withIdentifier(1);

    PrimaryDrawerItem item2 = new PrimaryDrawerItem()
            .withName(R.string.navigation_menu_item2)
            .withIdentifier(2);

    drawerResult = new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withActionBarDrawerToggleAnimated(true)
            .withHeader(R.layout.drawer_header)
            .addDrawerItems(item1)
            .addDrawerItems(item2)
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction transaction = manager.beginTransaction();
                    Fragment fragment = new Fragment();

                    switch (position){
                        case 1:
                            fragment = new ScreenOne();
                            break;
                        case 2:
                            fragment = new ScreenTwo(arrayItems);
                            break;
                    }
                    transaction.replace(R.id.content, fragment);
                    transaction.commit();

                    return false;
                }
            })
            .build();
}

@Override
public void onBackPressed(){
    if(drawerResult.isDrawerOpen()){
        drawerResult.closeDrawer();
    }
    else{
        super.onBackPressed();
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



@Override
public void onFragmentInteraction(String msg) {
    arrayItems.add(msg);
}

}

ScreenOne或fragment1

public class ScreenOne extends Fragment {

Button btnAdd;
EditText et;
private OnFragmentInteractionListener mListener;
ArrayList<String> items;



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

    btnAdd = (Button) view.findViewById(R.id.btnAdd);
    et = (EditText) view.findViewById(R.id.et);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String str = et.getText().toString();
            mListener.onFragmentInteraction(str);
            items.add(str);
            //updateDetail();
        }
    });

    return view;
}


public interface OnFragmentInteractionListener {

    void onFragmentInteraction(String msg);
}



@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " должен реализовывать интерфейс OnFragmentInteractionListener");
    }
}

public void updateDetail() {
    // генерируем некоторые данные
    String newTime = String.valueOf(System.currentTimeMillis());
    // Посылаем данные Activity
    mListener.onFragmentInteraction(newTime);
}

}

ScreenTwo或fragment2

public class ScreenTwo extends Fragment {

ArrayAdapter<String> adapter;
ArrayList<String> itemArray;

public ScreenTwo(ArrayList<String> itemArray){
    this.itemArray = itemArray;
}

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

    ListView listView = (ListView) view.findViewById(R.id.lvName);

    itemArray = new ArrayList<>();
    itemArray.clear();

    adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, itemArray);
    listView.setAdapter(adapter);
    return view;
}

1 个答案:

答案 0 :(得分:0)

我的猜测是你可以在你的界面OnFragmentInteractionListener中添加第三种方法,它会返回List<String> links,它将是ScreenOne存储的链接列表。

ScreenTwo被附加(在onAttach(Activity)回调中)到活动时,它将检索此列表并基于它构建UI。

另一个好处是声明另一个“监听器”接口,因此每次调用onFragmentInteraction(String)时,您都会通知所有听众有关发生的更改。