2

我正在尝试学习如何在 android 中使用 Fragments。我创建了单独的类和布局。我无法理解我应该如何将它们全部链接起来。我的主要课程到底有什么?有人可以准确地演示如何以非常基本的方式使用片段吗?

4

7 回答 7

3

请先阅读内容,因为我认为我有非常基础的知识。下面是一个例子:

主要活动:

public class MainActivity extends Activity implements OnClickListener{

private final String TAG = "MainActivity";
private int btn00Clicks = 0;
private int btn01Clicks = 0;

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

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Fragment mSelectedFragment = null;

    switch (v.getId()) {
    case R.id.btn00:    
        Bundle mBundle00 = new Bundle();
        String clicks00 = Integer.toString(btn00Clicks);
        mBundle00.putString("btn00_clicks", clicks00);
        mSelectedFragment = new Fragment00();
        mSelectedFragment.setArguments(mBundle00);

        if (mSelectedFragment != null) {
            FragmentManager mFragmentManager = getFragmentManager();
            mFragmentManager.beginTransaction()
            .replace(R.id.fragment00ID, mSelectedFragment).commit();
        }
        btn00Clicks++;

        break;
    case R.id.btn01:    
        Bundle mBundle01 = new Bundle();
        String clicks01 = Integer.toString(btn01Clicks);
        mBundle01.putString("btn01_clicks", clicks01);
        mSelectedFragment = new Fragment01();
        mSelectedFragment.setArguments(mBundle01);

        if (mSelectedFragment != null) {
            FragmentManager mFragmentManager = getFragmentManager();
            mFragmentManager.beginTransaction()
            .replace(R.id.fragment00ID, mSelectedFragment).commit();
        }
        btn01Clicks++;
    }
}

}

片段00.java:

public class Fragment00 extends Fragment {

private final String TAG = "Fragment00";
TextView mTv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.fragment00, null);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    mTv = (TextView) getView().findViewById(R.id.fragment00Tv00);

    if (getArguments() != null) {
        String str = getArguments().getString("btn00_clicks").toString();
        mTv.setText("the Button was clicked "+str+ " time(s)");
        Log.i(TAG, "onActivityCreated(): "+str);
    }else {
        Log.i(TAG, "onActivityCreated(): getArguments() is NULL");
    }
}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
}

}

片段01.java:

public class Fragment01 extends Fragment {

private static final String TAG = "Fragment01";
TextView mTv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment01, null);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    mTv = (TextView) getView().findViewById(R.id.fragment01Tv00);

    if (getArguments() != null) {
        String str = getArguments().getString("btn01_clicks").toString();
        mTv.setText("the Button was clicked "+str+ " time(s)");
        Log.i(TAG, "onActivityCreated(): "+str);
    }else {
        Log.i(TAG, "onActivityCreated(): getArguments() is NULL");
    }
}

}

MainActivity_layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.MainActivity"
tools:ignore="MergeRootFrame">

    <RelativeLayout
        android:id="@+id/mainRelativeLayout00"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_vertical">
        <Button
            android:id="@+id/btn00"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="fragment_one"
            android:onClick="onClick"></Button>
        <Button
            android:id="@+id/btn01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn00"
            android:text="Fragment two"
            android:onClick="onClick"></Button>
        <fragment
            android:name="com.example.fragments01.Fragment00"
            android:id="@+id/fragment00ID"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/btn01">
        </fragment>
    </RelativeLayout>

Fragment00_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.Fragment00"
tools:ignore="MergeRootFrame"
android:background="#00ffff">

<RelativeLayout
        android:id="@+id/fragment00RelativeLayout00"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_vertical">
        <TextView
            android:id="@+id/fragment00Tv00"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        </TextView>
</RelativeLayout>

Fragment01_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.Fragment01"
tools:ignore="MergeRootFrame"
android:background="#ffff00">

<RelativeLayout
        android:id="@+id/fragment01RelativeLayout00"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_vertical">
        <TextView
            android:id="@+id/fragment01Tv00"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Fragment two">
        </TextView>
        <Button
            android:id="@+id/fragment01Btn00"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button of fragment two"
            android:layout_below="@+id/fragment01Tv00">
        </Button>
</RelativeLayout>

于 2014-05-27T20:53:00.250 回答
2

在您的主类中,您生成一个或多个片段......虽然您生成每个片段,但它与 Activity 非常相似,但有自己的生命周期(google it)。

这是片段的示例:

public class DummySectionFragment3 extends Fragment 
{
    public DummySectionFragment3() {
    }

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

        View rootView = inflater.inflate(R.layout.exercise_layout,
                container, false);
        return rootView;
    }
}

在 OnCreateView() 方法中,您执行通常对活动执行的操作。我的 Main 类包含在片段之间切换的 SectionsPagerAdapter(API 示例中的寻呼机)创建 2 或 3 个片段并尝试它......我没有找到任何好的例子,所以我只是尝试了上面的方法。

于 2013-09-26T02:43:13.947 回答
1

http://www.c-sharpcorner.com/UploadFile/2fd686/fragments/

这是一个带有标签和片段的好链接。您还可以在 xml 中定义您的片段。

于 2014-02-24T16:17:51.433 回答
1

与 LetsAmrIt 发布的内容相同,只是另一个示例:

主要活动:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Comparator;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity implements MyListFragment.MovieSelectedListener
    {   
        Movie movie;
        ListView movieList;

        @SuppressWarnings("deprecation")
        @Override   
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            getWindow().setFormat(PixelFormat.RGBA_8888);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
            setContentView(R.layout.activity_main);

            try
            {
                FileInputStream fis = openFileInput("movies");

                if (fis != null)
                {
                    ObjectInputStream in = new ObjectInputStream(fis);

                    movie = (Movie) in.readObject();
                    in.close();

                    Toast.makeText(this, "Movies loaded.", Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e)
            {
                Toast.makeText(this, "No movies to load.", Toast.LENGTH_SHORT).show();
            }

            if (movie == null)
            {
                movie = new Movie();
                movie.addMovie("Harry Potter", "12 January", "Thriller", 4, "Some people", "Bad", "Someone", "Walmer Park");
            }
            loadFragments();
        }   


        public void loadFragments()
        {
            if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) 
            {     
                Log.d("Screen Size: ", "LARGE");
                // obtain the fragment manager
                FragmentManager fragmentManager = getFragmentManager();

                // determine if the fragment has already been loaded (may have happened)
                Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);

                // place fragment into container if not already there
                if (listfrag == null) {
                    // start a transaction that will handle the swapping in/out
                    FragmentTransaction fragmentTransaction = fragmentManager
                            .beginTransaction();

                    // multiple additions to the transaction can be done so that they
                    // changes will be done simultaneously
                    MyListFragment fragment1 = new MyListFragment();                
                    fragmentTransaction.add(R.id.fragment_container, fragment1);

                    ViewFragment fragment2 = new ViewFragment();
                    fragmentTransaction.add(R.id.details_container, fragment2);

                    Bundle args = new Bundle();
                    args.putSerializable("Movie", movie);
                    fragment1.setArguments(args);

                    // commit the changes, i.e. do it!
                    fragmentTransaction.commit();
                }
            }
            else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
                Log.d("Screen Size: ", "NORMAL");
                // obtain the fragment manager
                FragmentManager fragmentManager = getFragmentManager();

                // determine if the fragment has already been loaded (may have happened)
                Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);

                // place fragment into container if not already there
                if (listfrag == null) {
                    // start a transaction that will handle the swapping in/out
                    FragmentTransaction fragmentTransaction = fragmentManager
                            .beginTransaction();

                    // multiple additions to the transaction can be done so that they
                    // changes will be done simultaneously
                    MyListFragment fragment = new MyListFragment();
                    fragmentTransaction.add(R.id.fragment_container, fragment);

                    Bundle args = new Bundle();
                    args.putSerializable("Movie", movie);
                    fragment.setArguments(args);

                    // commit the changes, i.e. do it!
                    fragmentTransaction.commit();
                }
            } 
            else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
                Log.d("Screen Size: ", "SMALL");
            }
            else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     
                Log.d("Screen Size: ", "XLARGE");
                Log.d("Screen Size: ", "LARGE");
                // obtain the fragment manager
                FragmentManager fragmentManager = getFragmentManager();

                // determine if the fragment has already been loaded (may have happened)
                Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);

                // place fragment into container if not already there
                if (listfrag == null) {
                    // start a transaction that will handle the swapping in/out
                    FragmentTransaction fragmentTransaction = fragmentManager
                            .beginTransaction();

                    // multiple additions to the transaction can be done so that they
                    // changes will be done simultaneously
                    MyListFragment fragment1 = new MyListFragment();                
                    fragmentTransaction.add(R.id.fragment_container, fragment1);

                    ViewFragment fragment2 = new ViewFragment();
                    fragmentTransaction.add(R.id.details_container, fragment2);

                    Bundle args = new Bundle();
                    args.putSerializable("Movie", movie);
                    fragment1.setArguments(args);

                    // commit the changes, i.e. do it!
                    fragmentTransaction.commit();
                }
            }
            else {
                Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu items for use in the action bar
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main, menu);
            return true;
        }

        public void pushFragment(Movie curMovie) {
            // obtain the fragment manager
            FragmentManager fragmentManager = getFragmentManager();

            // start a transaction that will handle the swapping in/out
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();

            // add new fragment, BUT remember previous one, so that BACK button
            // returns to it
            ViewFragment fragment = new ViewFragment();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.addToBackStack("view");

            Bundle args = new Bundle();
            args.putSerializable("curMovie", curMovie);
            fragment.setArguments(args);

            // commit the changes, i.e. do it!
            fragmentTransaction.commit();
        }

        @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. 
            MyListFragment fragment = (MyListFragment) getFragmentManager().findFragmentById(R.id.fragment_container);
            switch(item.getItemId()) 
            {
            case R.id.action_about:
                About();
                return true;
            case R.id.action_add:
                addMovie();
                return true;
            case R.id.sort_Title:
                fragment.sortTitle();
                return true;
            case R.id.sort_Date:
                fragment.sortDateViewed();
                return true;
            case R.id.sort_Rating:
                fragment.sortRating();
                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub

            if (requestCode == 1)
            {
                if (resultCode == RESULT_OK)
                {
                    String title = data.getStringExtra("titleText");
                    String genre = data.getStringExtra("genreText");
                    String actors = data.getStringExtra("actorsText");
                    int rating = data.getIntExtra("ratingValue", 0);
                    String date = data.getStringExtra("dateWatched");
                    String watchedWith = data.getStringExtra("watchedWithText");
                    String watchedAt = data.getStringExtra("watchedAtText");
                    String comment = data.getStringExtra("commentText");                
                    movie.addMovie(title, date, genre, rating, actors, comment, watchedWith, watchedAt);
                    write();
                }
            }       
            super.onActivityResult(requestCode, resultCode, data);
        }

        public void write()
        {
            try
            {
                FileOutputStream fos = openFileOutput("movies", Context.MODE_PRIVATE);
                ObjectOutputStream out = new ObjectOutputStream(fos);
                out.writeObject(movie);
                fos.close();
                Toast.makeText(this, "Movies saved.", Toast.LENGTH_SHORT).show();
            }
            catch (Exception e)
            {
                Toast.makeText(this, "Movies could not be saved.", Toast.LENGTH_SHORT).show();
            }
        }

        public void addMovie()
        {
            Intent intentAdd = new Intent(MainActivity.this, AddMovie.class);
            startActivityForResult(intentAdd, 1);
        }

        public void About()
        {
            Intent intentAbout = new Intent(this, About.class);
            startActivity(intentAbout);
        }

        public void addDetails(Movie curMovie)
        {
            // obtain the fragment manager
            FragmentManager fragmentManager = getFragmentManager();

            // start a transaction that will handle the swapping in/out
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            ViewFragment fragment = new ViewFragment();
            // REPLACE the existing fragment with another one
            fragmentTransaction.replace(R.id.details_container, fragment);
            Bundle args = new Bundle();
            args.putSerializable("curMovie", curMovie);
            fragment.setArguments(args);
            // commit the changes, i.e. do it!
            fragmentTransaction.commit();
        }

        @Override
        public void onMovieSelected(String movieName) {
            // TODO Auto-generated method stub

            if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) 
            {               
                Log.d("Screen Size: ", "LARGE");

                Movie current = movie.getMovie(movieName);
                Context context = getApplicationContext();
                CharSequence text = current.MovieTitle;
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                addDetails(current);
            }
            else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
                Log.d("Screen Size: ", "NORMAL");


                Movie current = movie.getMovie(movieName);
                Context context = getApplicationContext();
                CharSequence text = current.MovieTitle;
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                pushFragment(current);
            } 
            else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
                Log.d("Screen Size: ", "SMALL");
            }
            else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     
                Log.d("Screen Size: ", "XLARGE");
            }
            else {
                Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
            }
        }


        @Override
        public void onDeleteSelected(String movie, MovieAdapter adapter) {
            // TODO Auto-generated method stub
            this.movie.deleteMovie(movie);
            adapter.notifyDataSetChanged();
            write();
        }
    }

电影适配器:

import java.util.List;
import android.content.Context;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;

public class MovieAdapter extends ArrayAdapter<Movie> {
    private Context context;
    private List<Movie> movies;

    public MovieAdapter(Context context, List<Movie> movies)
    {
        super(context, R.layout.movie_layout, movies);
        this.context = context;
        this.movies = movies;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View movieView = convertView;

        if(movieView == null)
        {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            movieView = inflater.inflate(R.layout.movie_layout, parent, false);
        } 

        movieView.setTag(movies.get(position));

        TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
        TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
        RatingBar ratingBar = (RatingBar) movieView.findViewById(R.id.ratingBar);

        txtTitle.setText(movies.get(position).MovieTitle);
        txtDate.setText("Date Viewed: "+movies.get(position).dateViewed);
        ratingBar.setIsIndicator(true);
        ratingBar.setNumStars(movies.get(position).rating);
        ratingBar.setRating(movies.get(position).rating);          
        return movieView;
    }

}

列表片段:

import java.util.Comparator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.util.Log;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;

public class MyListFragment extends Fragment{

    Movie movie;
    MovieAdapter adapter;
    MovieSelectedListener callBack;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View view = inflater.inflate(R.layout.list_fragment, container, false);

        ListView movieList = (ListView)view.findViewById(R.id.movieList);

        movieList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                TextView movie = (TextView)view.findViewById(R.id.txtTitle);
                String title = movie.getText().toString();
                callBack.onMovieSelected(title);
            }
        });     

        if (getArguments() != null)
            movie = (Movie)getArguments().getSerializable("Movie");
        Log.v("PASSED","Got here");
        adapter = new MovieAdapter(getActivity(), movie.movies);
        movieList.setAdapter(adapter);
        movieList.setLongClickable(true);
        movieList.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setMessage("Are you sure you want to delete this movie?");
                dialog.setTitle("Alert Message");
                dialog.setCancelable(false);
                dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        TextView movie = (TextView)view.findViewById(R.id.txtTitle);
                        String title = movie.getText().toString();
                        callBack.onDeleteSelected(title, adapter);

                    }
                });
                dialog.setNegativeButton("No",new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub      
                    }
                });
                dialog.show();
                return false;
            }
        });
        return view;
    }


    public interface MovieSelectedListener
    {
        public void onMovieSelected(String movie);
        public void onDeleteSelected(String movie, MovieAdapter adapter);
    }

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

    public void sortTitle()
    {

        adapter.sort(new Comparator<Movie>() {
            public int compare(Movie lhs, Movie rhs) {
                return lhs.MovieTitle.compareTo(rhs.MovieTitle);
            }
        });
        adapter.notifyDataSetChanged();
    }

    public void sortDateViewed()
    {

        adapter.sort(new Comparator<Movie>() {
            public int compare(Movie lhs, Movie rhs) {
                return lhs.dateViewed.compareTo(rhs.dateViewed);
            }
        });
        adapter.notifyDataSetChanged();
    }

    public void sortRating()
    {

        adapter.sort(new Comparator<Movie>() {
            public int compare(Movie lhs, Movie rhs) {
                return ((Integer)lhs.rating).compareTo(rhs.rating);
            }
        });
        adapter.notifyDataSetChanged();
    }
}

查看片段

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;

public class ViewFragment extends Fragment {

    Movie curMovie = new Movie("Empty", "Empty", "Empty", 5, "Empty", "Empty", "Empty", "Empty");
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View view = inflater.inflate(R.layout.view_fragment, container, false);
        if (getArguments() != null)
            curMovie = (Movie)getArguments().getSerializable("curMovie");

        TextView titleTxt = (TextView)view.findViewById(R.id.titleTxt);
        titleTxt.setText(curMovie.MovieTitle);
        TextView genreTxt = (TextView)view.findViewById(R.id.genreTxt);
        genreTxt.setText(curMovie.genre);
        TextView actorsTxt = (TextView)view.findViewById(R.id.actorsTxt);
        actorsTxt.setText(curMovie.actors);
        RatingBar ratingRes = (RatingBar)view.findViewById(R.id.ratingRes);
        ratingRes.setIsIndicator(true);
        ratingRes.setNumStars(curMovie.rating);
        ratingRes.setRating(curMovie.rating);
        TextView dateWatchedTxt = (TextView)view.findViewById(R.id.dateWatchedTxt);
        dateWatchedTxt.setText(curMovie.dateViewed);
        TextView watchedWithTxt = (TextView)view.findViewById(R.id.watchedWithTxt);
        watchedWithTxt.setText(curMovie.viewedWith);
        TextView watchedAtTxt = (TextView)view.findViewById(R.id.watchedAtTxt);
        watchedAtTxt.setText(curMovie.viewedWhere);
        TextView commentTxt = (TextView)view.findViewById(R.id.commentTxt);
        commentTxt.setText(curMovie.comments);

        // Inflate the layout for this fragment
        return view;
    }
}

电影:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Movie implements Serializable 
{
    String MovieTitle, dateViewed, actors, genre, comments, viewedWith, viewedWhere;
    int rating;
    public Movie(String MovieTitle, String dateViewed, String genre, int rating, String actors, String comments, String viewedWith, String viewedWhere)
    {
        this.MovieTitle = MovieTitle;
        this.dateViewed = dateViewed;
        this.genre = genre;
        this.rating = rating;
        this.actors = actors;
        this.comments = comments;
        this.viewedWith = viewedWith;
        this.viewedWhere = viewedWhere;
    }
    final List<Movie> movies = new ArrayList<Movie>();

    public Movie(){     
    }

    public void addMovie(String MovieTitle, String dateViewed, String genre, int rating, String actors, String comments, String viewedWith, String viewedWhere)
    {
        movies.add(new Movie(MovieTitle, dateViewed, genre, rating, actors, comments, viewedWith, viewedWhere));
    }

    public void deleteMovie(String movieTitle)
    {
        Movie toDelete = getMovie(movieTitle);
        movies.remove(toDelete);
    }

    public Movie getMovie(String movie)
    {
        for(Movie mov:movies)
        {
            if(mov.MovieTitle.equals(movie))
            {
                return mov;
            }           
        }
        return null;
    }
}

添加电影:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;

public class AddMovie extends Activity 
{
    EditText title2;
    EditText genre2;
    EditText actors2;
    RatingBar rating2;
    EditText date2;
    EditText watchedWith2;
    EditText watchedAt2;
    EditText comment2;

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

        //savedInstance
        title2 = (EditText)findViewById(R.id.title);
        genre2 = (EditText)findViewById(R.id.genre);
        actors2 = (EditText)findViewById(R.id.actors);
        rating2 = (RatingBar)findViewById(R.id.rating);
        date2 = (EditText)findViewById(R.id.dateWatched);
        watchedWith2 = (EditText)findViewById(R.id.watchedWith);
        watchedAt2 = (EditText)findViewById(R.id.watchedAt);
        comment2 = (EditText)findViewById(R.id.comment);

        if ((savedInstanceState != null) && (savedInstanceState.containsKey("TITLE_STATE_KEY")))
        {
            title2.setText(savedInstanceState.getString("TITLE_STATE_KEY"));
            actors2.setText(savedInstanceState.getString("ACTORS_STATE_KEY"));
            genre2.setText(savedInstanceState.getString("GENRE_STATE_KEY"));
            comment2.setText(savedInstanceState.getString("GC_STATE_KEY"));
            watchedWith2.setText(savedInstanceState.getString("WITH_STATE_KEY"));
            watchedAt2.setText(savedInstanceState.getString("LOCATION_STATE_KEY"));
            date2.setText(savedInstanceState.getString("DATE_STATE_KEY"));
            rating2.setRating(savedInstanceState.getFloat("RATING_STATE_KEY"));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.add_movie, 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.
        switch(item.getItemId()) 
        {
        case R.id.action_settings:        
            return true;
        case R.id.action_done:
            done();
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public void done()
    {
        EditText title = (EditText)findViewById(R.id.title);
        String titleText = title.getText().toString();

        EditText genre = (EditText)findViewById(R.id.genre);
        String genreText = genre.getText().toString();

        EditText actors = (EditText)findViewById(R.id.actors);
        String actorsText = actors.getText().toString();

        RatingBar rating = (RatingBar)findViewById(R.id.rating);
        int ratingValue = Math.round(rating.getRating());

        EditText date = (EditText)findViewById(R.id.dateWatched);
        String dateWatched = date.getText().toString();

        EditText watchedWith = (EditText)findViewById(R.id.watchedWith);
        String watchedWithText = watchedWith.getText().toString();

        EditText watchedAt = (EditText)findViewById(R.id.watchedAt);
        String watchedAtText = watchedAt.getText().toString();

        EditText comment = (EditText)findViewById(R.id.comment);
        String commentText = comment.getText().toString();          

        Intent intent = new Intent(AddMovie.this, MainActivity.class);

        intent.putExtra("titleText", titleText);
        intent.putExtra("genreText", genreText);
        intent.putExtra("actorsText", actorsText);
        intent.putExtra("ratingValue", ratingValue);
        intent.putExtra("dateWatched", dateWatched);
        intent.putExtra("watchedWithText", watchedWithText);
        intent.putExtra("watchedAtText", watchedAtText);
        intent.putExtra("commentText", commentText);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle saveInstanceState)
    {
        saveInstanceState.putString("TITLE_STATE_KEY", title2.getText().toString());
        saveInstanceState.putString("GENRE_STATE_KEY", genre2.getText().toString());
        saveInstanceState.putString("GC_STATE_KEY", comment2.getText().toString());
        saveInstanceState.putString("DATE_STATE_KEY", date2.getText().toString());
        saveInstanceState.putString("ACTORS_STATE_KEY", actors2.getText().toString());
        saveInstanceState.putString("WITH_STATE_KEY", watchedWith2.getText().toString());
        saveInstanceState.putString("LOCATION_STATE_KEY", watchedAt2.getText().toString());
        saveInstanceState.putFloat("RATING_STATE_KEY", rating2.getRating());

        super.onSaveInstanceState(saveInstanceState);
    }
}
于 2014-09-05T09:18:38.527 回答
0

基本是这样的:

创建一个 Activity 和 2 个片段。

如果 FragmantA 中发生了某些事情,fragmentB 中的某些内容应该会发生变化。因此,Activity 将 Fragment A 和 B 链接在一起。你需要什么:一个接口。

因此,使用具有正确属性的方法创建一个接口(不要忘记数据类型)。现在您可以在您的活动中实现该接口。

在此之后,您应该在 onActivityCreated 方法中初始化 FragmentA 中的接口。执行更改并将数据发送到 Activity 中的接口方法。使用 FragmentManager 创建对 FragmentB 的引用。现在您可以将数据/更改发送到 FragmentB。

我希望你明白这一点;)。干杯

于 2014-04-14T21:26:00.507 回答
0

我做了一个示例项目,它没有使用ViewPager和所有奇怪的东西,只是Stack OverflowActivity上的和Fragment此处之间的链接以及Code Review上的相同内容来演示它,单击任一链接以查看项目。

于 2014-07-31T08:02:21.033 回答
-1

我使用此链接开始 http://www.techotopia.com/index.php/Using_Fragments_in_Android_-_A_Worked_Example

这家伙使用 2 种不同类型的侦听器,并在第一个片段上接收用户输入。第二个片段输出数据!

祝你好运!

于 2013-11-11T10:10:15.210 回答