当单击行中的按钮时,如何将片段中的listview中的行传递到同一活动中另一个片段的listview中?

时间:2014-11-11 00:53:47

标签: android listview android-fragments android-listview

我在一个活动中有两个片段,main_activity.xml中有一个ViewPager元素。我创建了两个不同的类,它们为每个片段释放Fragment类并覆盖onCreateView方法。第一个片段是频道列表。所以这是一个列表视图,它的每一行都包含一个textview和一个按钮。我想当用户单击按钮时,将行传递给第二个片段中的listView。我在ChannelsFragment中创建了一个名为 FavButtonClickedListener 的接口,并在 MainActivity.java 中覆盖了此接口。然后我将 onAttach()方法添加到ChannelsFragment中以引用MainActivity。在ChannelsFragment类的Adapter的getView方法中,我已经将clicklistener设置为每行中的imageButtons,并且我调用了 whenFavButtonClicked.onFavButtonClicked(); 我的代码适用于SharedPreferences hovewer我需要重启应用程序以查看更改在收藏夹列表中。我想动态添加行。我不知道我错在哪里请帮助我

ChannelsFragment:

public class ChannelsFragment extends Fragment {

ViewGroup rootVg;
Context context;
FavButtonClickedListener whenFavButtonClicked;

private final List<String> favValues = new ArrayList<String>();

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.channels_list_layout, container, false);
     final ListView channelsList = (ListView) rootView.findViewById(R.id.channelsListView);

     String[] chNames = new String[]{"ChA","ChB","ChC"};


     final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < chNames.length; ++i) {
          list.add(chNames[i]);
        }

       //set adapter to listview
        MyListAdapter listAdapter = new  MyListAdapter(getActivity(),chNames);
        channelsList.setAdapter(listAdapter);

        return rootView;
    }

 public interface FavButtonClickedListener {
        public void onFavButtonClicked(int position,List<String>favs);
    }

 @Override
 public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = getActivity();

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
             whenFavButtonClicked = (FavButtonClickedListener)context;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
 }

ChannelsFragment Adapter类:

public class MyListAdapter extends ArrayAdapter<String>{

      private final Context context;
      private final String[] values;
      URL channelUrl;


      public MyListAdapter(Context context, String[] values) {
        super(context, R.layout.list_item_complex, values);
        this.context = context;
        this.values = values;
      }

      @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
             return 0;
        }
      public long getCount(int position) {
            // TODO Auto-generated method stub
             return values.length;
        }

      @Override
      public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.list_item_complex, parent, false);
        TextView chNameText = (TextView) rowView.findViewById(R.id.chName);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.chImage);
        final ImageButton imageButton = (ImageButton)rowView.findViewById(R.id.starButon);
        Button chButton = (Button)rowView.findViewById(R.id.chButon);


        chNameText.setText(values[position]);

        //Set the channels' logo appropriately
        if(values[position].equals("CHa")){
            imageView.setImageResource(R.drawable.CHaImage);
            imageButton.setId(0);
        }else if(values[position].equals("CHb")){
            imageView.setImageResource(R.drawable.CHbImage);
            imageButton.setId(1);
        }else if(values[position].equals("Chc")){
            imageView.setImageResource(R.drawable.CHcImage);
            imageButton.setId(2);
        }else{
            imageView.setImageResource(R.drawable.defult_bacground_logo);

         }
        }
       //Determine the target url for each channel correctly
        chButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent i = new Intent("android.intent.action.Activity2");
                String chName = null;

                if(values[position].equals("CHa")){

                     i.putExtra("CHa", "http://www.cha.com/");
                     chName = "CHa";
                     i.putExtra("nameofCh", ChName);
                     startActivity(i);   
                 }
                if(values[position].equals("CHb")){

                    i.putExtra("CHb", "http://www.chb.com/");
                    chName = "CHb";
                    i.putExtra("nameofCh",ChName);
                    startActivity(i);
                }
                if(values[position].equals("CHc")){

                    i.putExtra("CHc", "http://www.chc.com/");
                    chName = "CHc";
                    i.putExtra("nameofCh",ChName);
                    startActivity(i);
                }
        });

        final Context konteks;
        konteks = this.getContext();

        //set button click for favorite channels list
        // I use this imageButton for create a favorites list in listview in FavoritesChannels 
        //fragment. I want when the user click this button, the row that has been clicked, get    
        //passed to FavoritesChannels fragment

        imageButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                imageButton.setImageResource(R.drawable.button_states_star);

                SharedPreferences prefs = konteks.getSharedPreferences("favorites",Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();

                if(imageButton.getId()==0){


                    editor.putBoolean("CHaChecked", true);
                    editor.commit();
                    favValues.add("CHa");
                    whenFavButtonClicked.onFavButtonClicked(position,favValues);
                    Toast.makeText(getActivity(), "CHa have been added to favlist", Toast.LENGTH_SHORT).show();

                }
                else if(imageButton.getId()==1){

                    editor.putBoolean("CHbChecked", true);
                    favValues.add("CHb");
                    editor.commit();
                    whenFavButtonClicked.onFavButtonClicked(position,favValues);
                    Toast.makeText(getActivity(), "CHb have been added to favlist", Toast.LENGTH_SHORT).show();

                }
                else if(imageButton.getId()==2){

                    editor.putBoolean("CHcChecked", true);
                    favValues.add("CHc");
                    editor.commit();
                    whenFavButtonClicked.onFavButtonClicked(position,favValues);
                    Toast.makeText(getActivity(), "CHc have been added to favlist", Toast.LENGTH_SHORT).show();

                }else{

                    Toast.makeText(getActivity(), "CH have been added to favlist", Toast.LENGTH_SHORT).show();
                }

            }
        });

return rowView;
      } 
 }

MainActivity.java:

onFavButtonClicked()实现位于文件末尾

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener,KanallarFragment.FavButtonClickedListener {

   private static final int NUM_PAGES = 2;
   public SharedPreferences prefs;
   FragmentTransaction fragmentTransaction;


/**
 * The pager widget, which handles animation and allows swiping horizontally to access previous
 * and next wizard steps.
 */
private ViewPager mPager;

/**
 * The pager adapter, which provides the pages to the view pager widget.
 */
private PagerAdapter mPagerAdapter;

//Initiate Actionbar instance and define its tab names
private ActionBar actionBar;
private String[] tabs = { "Channels", "Favorites"};


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

    FragmentManager fragMgr = getSupportFragmentManager();
    fragmentTransaction = fragMgr.beginTransaction();

    fragmentTransaction.add(new FavoriteFragment(), "favsFragment");
    fragmentTransaction.add(new ChannelsFragment(), "channelsFragment");

        // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);   

    //ViewPager's PageChangeListener
    mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {

            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

   //Retrieve actionbar and set some properties
    actionBar = getSupportActionBar();
  //actionBar.setHomeButtonEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 
    actionBar.setStackedBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_gradient));
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(true);

    // Adding Tabs to actionbar
     for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }

   for(int i = 0; i<actionBar.getTabCount(); i++){

            LayoutInflater inflater = LayoutInflater.from(this);
            View customView = inflater.inflate(R.layout.tab_layout, null);
            TextView titleTV = (TextView) customView.findViewById(R.id.action_custom_title);
            titleTV.setText(tabs[i]);
            ImageView tabImage = (ImageView)customView.findViewById(R.id.tab_icon);

            if(i==0){
                tabImage.setImageResource(R.drawable.television_icon_64);

            }else{
                tabImage.setImageResource(R.drawable.star_icon);

            }
         actionBar.getTabAt(i).setCustomView(customView);
        }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/*public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub
    mPager.setCurrentItem(tab.getPosition());

}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}*/

private class ViewPagerAdapter extends FragmentStatePagerAdapter {
    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
     public Fragment getItem(int position) {



        switch (position){
            case 0:
                return new ChannelsFragment();
            case 1:
                return new FavoritesFragment();
            }
            return null;
    }

    @Override

    public int getCount() {
        return NUM_PAGES;
    }
}

@Override
public void onTabReselected(Tab arg0,FragmentTransaction arg1) {
    // TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab arg0,FragmentTransaction arg1) {
    // TODO Auto-generated method stub
    mPager.setCurrentItem(arg0.getPosition());
}
@Override
public void onTabUnselected(Tab arg0,FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

public void onFavButtonClicked(int position,List<String>favs) {
    // TODO Auto-generated method stub


     FavoritesFragment favFrag = (FavoritesFragment)getSupportFragmentManager().findFragmentByTag("favsFragment");

     if(favFrag !=null){

     favFrag.updateList(position,favs);
     }
}

包含updateList()方法的FavoritesFragment类:

public class FavorilerFragment extends Fragment {

Context context;


private final List<String> values = new ArrayList<String>();
private final List<String> favValues = new ArrayList<String>();
ListView listView;
TextView textView;

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     Context context = getActivity();
     ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.favorites_list_layout, container, false);
     listView = (ListView)rootView.findViewById(R.id.f_channels_ListView);
     textView = (TextView)rootView.findViewById(R.id.favListMessage);


     SharedPreferences prefs = context.getSharedPreferences("favorites",getActivity().MODE_PRIVATE);


     //-----SharedPreferences values for adapter----
     if(prefs.getBoolean("CHaChecked", false)){

        values.add("Cha"); 
    }
     if(prefs.getBoolean("CHbChecked", false)){

            values.add("Chb"); 
        }
     if(prefs.getBoolean("ChcChecked", false)){

            values.add("Chc"); 
        }

     //-----------------------------------------------

     if(values.size() == 0){

         textView.setText("Favorites List is empty");

     }else{

         textView.setText("");
    }

     MyListAdapter adapter = new MyListAdapter(getActivity(),values);
     listView.setAdapter(adapter);

     return rootView;
    }



 @Override
 public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = getActivity();
    }

 public void updateList(int position,List<String> argfavValues){

     for(int a= 0;a<argFavValues.size();a++){

         favValues.add(argFavValues.get(a));

     }

     MyListAdapter = new MyListAdapter(getActivity(),favValues);
     adaptor.notifyDataSetChanged();
     listView.setAdapter(adapter);

}

 public static class MyListAdapter extends ArrayAdapter<String>{

      private final Context context;
      private final List<String> values = new ArrayList<String>();
      URL ChUrl;


      public MyListAdapter(Context context, List<String> values) {
        super(context, R.layout.list_item_complex_fav, values);
        this.context = context;

        for(int i=0;i<values.size();i++){

            this.values.add(values.get(i));

        }
      }

      @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
             return 0;
        }

      public long getCount(int position) {
            // TODO Auto-generated method stub

             return values.size();
        }

      @Override
      public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.list_item_complex_fav, parent, false);
        TextView chNameText = (TextView) rowView.findViewById(R.id.ChName);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.ChannelsImage);
        Button chButton = (Button)rowView.findViewById(R.id.chButon);

       chNameText.setText(values.get(position));

        //Set the channels' logo appropriately
        if(values.get(position).equals("CHa")){
            imageView.setImageResource(R.drawable.CHaImage);

        }else if(values.get(position).equals("CHb")){
            imageView.setImageResource(R.drawable.CHbImage);

        }else if(values.get(position).equals("CHc")){
            imageView.setImageResource(R.drawable.CHcImage);


         else{
            imageView.setImageResource(R.drawable.default_logo);

        }

        return rowView; 
      }

 }

1 个答案:

答案 0 :(得分:0)

根据官方documentation,片段到片段的通信应该通过活动路由。

您需要在channel片段中创建一个接口,并定义一些回调方法,如onSelected。选择列表项后,使用活动上下文调用该接口方法:

public class ChannelsFragment extends ListFragment {
    OnItemSelectedListener mCallback;

    public interface OnItemSelectedListener {
        public void onSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallback = (OnItemSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement OnItemSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        mCallback.onSelected(position);
    }
}

然后,您的活动需要 implement ChannelFragment.OnItemSelectedListener 并定义回调方法。

public void onSelected(int position) {
    Fragment2 fragment = (Fragment2)
        getSupportFragmentManager().findFragmentById(R.id.fragment2);

    if (fragment != null) {
        fragment.updateValue(position);
    }
}

您可以通过参数传递数据。要将数据发送到另一个片段,请在片段中创建一个可以直接从活动调用的公共方法。