简体   繁体   English

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

[英]Java Passing Data From One Fragment's ListView To Another Fragment

Movie ListView Fragment Movie Info Fragment 电影ListView片段 电影信息片段

What I have is an app that has a database of movies, in my first tab fragment I have a listview which has all the movies in my database. 我所拥有的是一个具有电影数据库的应用程序,在我的第一个标签片段中,我具有一个列表视图,该列表视图包含数据库中的所有电影。 I want it so when I click a movie in the listview it grabs the movie's database id and moves to the next tab which displays the movie info. 我想要它,所以当我在列表视图中单击电影时,它将获取电影的数据库ID,并移至显示电影信息的下一个选项卡。

Main Activity (The activity that holds my tabs view pager) 主要活动(保存我的标签页查看器的活动)

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 (Where the movies database is displayed in a listview) 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;
}

} }

All Fragment-to-Fragment communication is done through the associated Activity. 所有片段到片段的通信都是通过关联的活动完成的。 Two Fragments should never communicate directly. 两个片段永远不要直接通信。

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

You can communicate the two fragments with a static variable in the MainActivity that you change in the first fragment and get the content of this variable in the second fragment. 您可以将两个片段与在第一个片段中更改的MainActivity中的静态变量进行通信,并在第二个片段中获取此变量的内容。

Update: 更新:

Create Movie.class, to save all the data of a one movie: 创建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
}

and in your MainActivity create a static variable of Movie : 然后在您的MainActivity中创建Movie的静态变量:

public static Movie movie;

In onClick method save the data of the movie: onClick方法中保存电影的数据:

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

And to get the movie in the second fragment: 并在第二个片段中获得电影:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM