Java将数据从一个片段的Lis​​tView传递到另一个片段

时间:2016-01-03 17:58:36

标签: java android fragment

Movie ListView Fragment Movie Info Fragment

我所拥有的是一个拥有电影数据库的应用程序,在我的第一个标签片段中,我有一个列表视图,其中包含我数据库中的所有电影。我想要它,所以当我点击列表视图中的电影时,它会抓取电影的数据库ID并移动到显示电影信息的下一个标签。

主要活动(保存我的标签视图寻呼机的活动)

public class MainActivity extends AppCompatActivity {
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

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

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

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu){
        getMenuInflater().inflate(R.menu.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 static class SectionsPagerAdapter extends FragmentPagerAdapter {
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new FragmentMain();
                case 1:
                    return new FragmentManuallyAddMovie();
                case 2:
                    return new FragmentAddInternetMovie();
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "MOVIES";
                case 1:
                    return "ADD";
                case 2:
                    return "SEARCH";
            }
            return null;
        }
    }

    public static class PlaceholderFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }
}

FragmentMain(电影数据库以列表视图显示的位置)

public class FragmentMain extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {

private MoviesDBHandler handler;
private SimpleCursorAdapter adapter;
private ListView lvMovies;

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

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

    handler = new MoviesDBHandler(this.getActivity());

    v.findViewById(R.id.btn_delete_all_movies).setOnClickListener(this);

    lvMovies = (ListView) v.findViewById(R.id.lv_movies);
    lvMovies.setEmptyView(v.findViewById(R.id.tv_instructionsa));

    lvMovies.setOnItemClickListener(this);
    lvMovies.setOnItemLongClickListener(this);
    return v;
}

@Override
public void onResume() {
    super.onResume();
    String[] from = {MoviesDBHelper.MOVIES_TITLE, MoviesDBHelper.MOVIES_GENRE, MoviesDBHelper.MOVIES_YEAR, MoviesDBHelper.MOVIES_PLOT, MoviesDBHelper.MOVIES_RATING, MoviesDBHelper.MOVIES_RUNTIME, MoviesDBHelper.MOVIES_IMAGE_URL};
    int[] to = {R.id.tv_title, R.id.tv_genre, R.id.tv_year, R.id.tv_plot, R.id.tv_rating, R.id.tv_runtime, R.id.img_movie_poster};

    adapter = new SimpleCursorAdapter(this.getActivity(), R.layout.movie_list_item, handler.getMovies(), from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if(columnIndex == cursor.getColumnIndex(MoviesDBHelper.MOVIES_IMAGE_URL)) {
                DatabaseDownloadImage task = new DatabaseDownloadImage((ImageView) view);
                task.execute(cursor.getString(columnIndex));
                return true;
            }
            return false;
        }
    });
    lvMovies.setAdapter(adapter);
}

public class DatabaseDownloadImage extends AsyncTask<String, Integer, Bitmap> {

    private ImageView imageView;

    public DatabaseDownloadImage(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        String address = params[0];
        HttpURLConnection connection = null;
        Bitmap b = null;

        try {
            URL url = new URL(address);
            connection = (HttpURLConnection) url.openConnection();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return null;
            }
            else {
                b = BitmapFactory.decodeStream(connection.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }

    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }
        imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 180, false));
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        //Delete all movies from database
        case R.id.btn_delete_all_movies:
            AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
            deleteMovieDialog.setTitle("Delete All Movies?");
            deleteMovieDialog.setIcon(R.drawable.ic_delete);
            deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.deleteAllMovies();
                    adapter.changeCursor(handler.getMovies());
                }
            });
            deleteMovieDialog.show();
            break;
    }
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
    AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
    deleteMovieDialog.setTitle("Delete Movie?");
    deleteMovieDialog.setIcon(R.drawable.ic_delete);
    deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.deleteMovie(id);
            adapter.changeCursor(handler.getMovies());
        }
    });
    deleteMovieDialog.show();
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

  

所有片段到片段的通信都是通过关联的方式完成的   活动。两个碎片永远不应该直接沟通。

http://developer.android.com/intl/es/training/basics/fragments/communicating.html

您可以使用您在第一个片段中更改的MainActivity中的静态变量传递这两个片段,并在第二个片段中获取此变量的内容。

更新

创建Movie.class,以保存一部电影的所有数据:

public class Movie() {

    String title;
    String genre;
    int year;
    String plot;
    int rating;
    int runtime;
    String img;

    public Movie(String title, String genre, int year, String plot, int rating, int runtime, String img) {
        this.title=title;
        this.genre=genre;
        this.year=year;
        this.plot=plot;
        this.rating=rating;
        this.runtime=runtime;
        this.img=img;
    }

    public String getTitle() {
        return title;
    } 
    public void setTitle(String title) {
        this.title=title;
    }

    //The same for the other variables
}

并在您的MainActivity中创建一个Movie的静态变量:

public static Movie movie;

onClick方法中保存电影的数据:

MainActivity.movie=new Movie(title, genre, year,plot,rating,runtime,img);

并将电影放入第二个片段:

String title=MainActivity.movie.getTitle();
String genre=MainActivity.movie.getGenre();
...