具有自定义cursorAdapter的itemlist将view.visible设置为错误的项目

时间:2015-01-19 11:32:27

标签: android listview imageview android-cursoradapter

我尝试使用oncontextitemselected将imageview从不可见设置为可见。但是当我点击listview时,imageview会在listview项目中随机变为可见,而不仅仅是在所选项目中。我怎么能解决这个问题?这是我的代码。

public class MainActivity extends Activity implements OnItemClickListener,
    OnClickListener {

private DbHandler dbHandler;
DbOpenHelper dbOpenhelper;
private MovieAdapter adapter;
private MediaPlayer mp;


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

    mp = MediaPlayer.create(this, R.raw.piratesofthecarribean);
    mp.start();

    dbHandler = new DbHandler(this);

    ListView listView = (ListView) findViewById(R.id.listView1);
    Cursor cursor = dbHandler.queryAll();
    startManagingCursor(cursor);

    adapter = new MovieAdapter(this, cursor);

    listView.setAdapter(adapter);
    listView.setOnItemClickListener(this);

    ImageView addMovie = (ImageView) findViewById(R.id.imageViewAddMovie);

    addMovie.setOnClickListener(this);

    registerForContextMenu(listView);

}
/// creating option menu///
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_options_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.remove_all:
        dbOpenhelper = new DbOpenHelper(this);
        SQLiteDatabase db = dbOpenhelper.getWritableDatabase();
        String sql = "DROP TABLE IF EXISTS " + DbConstants.TABLE_NAME;
        db.execSQL(sql);
        dbOpenhelper.onCreate(db);
        refreshTheOutput();
        adapter.notifyDataSetChanged();
        Toast.makeText(this, "No Movies To Show! Press Add To Add Movie", 
                Toast.LENGTH_SHORT).show();
            break;

    case R.id.imdbtopten:
        fill();
        refreshTheOutput();
            break;

    case R.id.exit:
        onBackPressed();
            break;

    case R.id.mute:
        mp.pause();
            break;

    case R.id.unmute:
        mp.start();
            break;


    }
    return true;
}

////creating context menu////
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    getMenuInflater().inflate(R.menu.item_context_menu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    long id = info.id;

    switch (item.getItemId()) {
    case R.id.itemDelete:
        dbHandler.delete(id);
        refreshTheOutput();
        return true;

    /// open edit only activity///
    case R.id.itemEdit:

        Movie m = dbHandler.query(id);

        Intent intent = new Intent(this, EditMovieActivity.class);
        intent.setAction(Intent.ACTION_EDIT);
        intent.putExtra("id", m.getId());
        intent.putExtra("name", m.getMovieName());
        intent.putExtra("plot", m.getMoviePlot());
        intent.putExtra("genre", m.getMovieGenre());
        intent.putExtra("director", m.getMovieDirector());
        intent.putExtra("cast", m.getMovieCast());
        intent.putExtra("trailer", m.getTrailerUrl());
        intent.putExtra("runtime", m.getMovieRuntime());
        intent.putExtra("year", m.getMovieReleasdYear());
        intent.putExtra("rating", m.getMovieRating());
        intent.putExtra("poster", m.getPosterUrl());

        startActivity(intent);

            break;

    /// give the option to reset the list to the default movies /// 
    case R.id.reset:
        dbOpenhelper = new DbOpenHelper(this);
        SQLiteDatabase db = dbOpenhelper.getWritableDatabase();
        String sql = "DROP TABLE IF EXISTS " + DbConstants.TABLE_NAME;
        db.execSQL(sql);
        dbOpenhelper.onCreate(db);
        fill();
        refreshTheOutput();
            break;


    case R.id.itemSawThat:
        ImageView sawThat = (ImageView) findViewById(R.id.imageViewSawThat);
        sawThat.setVisibility(View.VISIBLE);

            break;






    }

    return super.onContextItemSelected(item);
}




private void refreshTheOutput() {

    Cursor oldCursor = adapter.getCursor();
    Cursor newCursor = dbHandler.queryAll();
    startManagingCursor(newCursor);

    adapter.changeCursor(newCursor);

    stopManagingCursor(oldCursor);
    oldCursor.close();

}

// /fill top 10 imdb movies///

private void fill() {

    Movie TheShawshankRedemption = new Movie(
            "The Shawshank Redemption",
            "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
            "Crime | Drama",
            "Frank Darabont",
            "Tim Robbins, Morgan Freeman, Bob Gunton ",
            "http://www.youtube.com/watch?v=zdWZBvd0-pg&spfreload=10",
            "142 min",
            "9.3",
            "1994",
            "http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX214_AL_.jpg");

    Movie theGodfather = new Movie(
            "The Godfather",
            "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
            "Crime | Drama",
            "Francis Ford Coppola",
            "Marlon Brando, Al Pacino, James Caan",
            "http://www.youtube.com/watch?v=OfnUvYn6HoM&spfreload=10",
            "175 min",
            "9.2",
            "1972",
            "http://ia.media-imdb.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_SX214_AL_.jpg");

    Movie theGodfatherPartTwo = new Movie(
            "The Godfather: Part II",
            "The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.",
            "Crime | Drama",
            "Francis Ford Coppola",
            "Al Pacino, Robert De Niro, Robert Duvall ",
            "http://www.youtube.com/watch?v=GtuJdcnHEO4&spfreload=10",
            "200 min",
            "9.0",
            "1974",
            "http://ia.media-imdb.com/images/M/MV5BNDc2NTM3MzU1Nl5BMl5BanBnXkFtZTcwMTA5Mzg3OA@@._V1_SX214_AL_.jpg");

    Movie theDarkKnight = new Movie("The Dark Knight", 
            "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, "
            + "the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.", 
            "Action | Crime", "Christopher Nolan", "Christian Bale, Heath Ledger, Aaron Eckhart", 
            "http://www.youtube.com/watch?v=EXeTwQWrcwY&spfreload=10", 
            "152 min", 
            "9.0", 
            "2008", 
            "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SY317_CR0,0,214,317_AL_.jpg");

    Movie pulpFiction = new Movie("Pulp Fiction", "The lives of two mob hit men, a boxer, a gangster's wife, "
            + "and a pair of diner bandits intertwine in four tales of violence and redemption.",
            "Crime | Drama", "Quentin Tarantino", "John Travolta, Uma Thurman, Samuel L. Jackson ", 
            "http://www.youtube.com/watch?v=s7EdQ4FqbhY&spfreload=10",
            "154 min", 
            "8.9", 
            "1994", 
            "http://ia.media-imdb.com/images/M/MV5BMjE0ODk2NjczOV5BMl5BanBnXkFtZTYwNDQ0NDg4._V1_SY317_CR4,0,214,317_AL_.jpg");

    Movie Ilbuonoilbruttoilcattivo = new Movie("Il Buono, Il Brutto, Il Cattivo", 
            "A bounty hunting scam joins two men in an uneasy alliance against a third in a race to "
            + "find a fortune in gold buried in a remote cemetery.", "Western", "Sergio Leone", 
            "Clint Eastwood, Eli Wallach, Lee Van Cleef ", 
            "http://www.youtube.com/watch?v=dF8119NYeSQ&spfreload=10", 
            "161 min", 
            "8.9", 
            "1966", 
            "http://ia.media-imdb.com/images/M/MV5BOTQ5NDI3MTI4MF5BMl5BanBnXkFtZTgwNDQ4ODE5MDE@._V1_SX214_AL_.jpg");

    Movie TwelveAngryMen = new Movie("12 Angry Men", "A dissenting juror in a murder trial slowly manages to convince the others that the case is not as "
            + "obviously clear as it seemed in court.", 
            "Drama", "Sidney Lumet", "Henry Fonda, Lee J. Cobb, Martin Balsam", 
            "http://www.youtube.com/watch?v=A7CBKT0PWFA&spfreload=10", 
            "96 min", 
            "8.9", 
            "1957", 
            "http://ia.media-imdb.com/images/M/MV5BODQwOTc5MDM2N15BMl5BanBnXkFtZTcwODQxNTEzNA@@._V1_SX214_AL_.jpg");

    Movie SchindlerList = new Movie("Schindler's List", "In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their "
            + "persecution by the Nazis.", 
            "Biography", "Steven Spielberg", "Liam Neeson, Ralph Fiennes, Ben Kingsley", 
            "http://www.youtube.com/watch?v=JdRGC-w9syA&spfreload=10", 
            "195 min", 
            "8.9", 
            "1993", 
            "http://ia.media-imdb.com/images/M/MV5BMzMwMTM4MDU2N15BMl5BanBnXkFtZTgwMzQ0MjMxMDE@._V1_SX214_AL_.jpg");


    Movie LotrTheReturn = new Movie("The Lord of the Rings: The Return of the King", 
            "Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.", 
            "Adventure | Fantasy", "Peter Jackson", "Elijah Wood, Viggo Mortensen, Ian McKellen ", 
            "http://www.youtube.com/watch?v=r5X-hFf6Bwo&spfreload=10", 
            "201 min", 
            "8.9", 
            "2003", 
            "http://ia.media-imdb.com/images/M/MV5BMjE4MjA1NTAyMV5BMl5BanBnXkFtZTcwNzM1NDQyMQ@@._V1_SX214_AL_.jpg");

    Movie fightClub = new Movie("Fight Club", "An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club "
            + "that evolves into something much, much more...", 
            "Drama", "David Fincher", "Brad Pitt, Edward Norton, Helena Bonham Carter", 
            "http://www.youtube.com/watch?v=SUXWAEX2jlg&spfreload=10", 
            "139 min", 
            "8.9", 
            "1999", 
            "http://ia.media-imdb.com/images/M/MV5BMjIwNTYzMzE1M15BMl5BanBnXkFtZTcwOTE5Mzg3OA@@._V1_SX214_AL_.jpg");

    dbHandler.insert(TheShawshankRedemption);
    dbHandler.insert(theGodfather);
    dbHandler.insert(theGodfatherPartTwo);
    dbHandler.insert(theDarkKnight);
    dbHandler.insert(pulpFiction);
    dbHandler.insert(Ilbuonoilbruttoilcattivo);
    dbHandler.insert(TwelveAngryMen);
    dbHandler.insert(SchindlerList);
    dbHandler.insert(LotrTheReturn);
    dbHandler.insert(fightClub);

}

// / bulid custome adapter://////
public class MovieAdapter extends CursorAdapter {

    public MovieAdapter(Context context, Cursor c) {
        super(context, c);
    }


    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        String movieName = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_NAME));
        String movieGenre = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_GENRE));
        String itemPoster = cursor.getString(cursor
                .getColumnIndexOrThrow(DbConstants.MOVIE_POSTER));
        String movieRuntime = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_RUNTIME));
        String movieRating = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_RATING));
        String movieReleasedYear = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_YEAR_RELEASD));

        TextView name = (TextView) view
                .findViewById(R.id.textViewMovieName);
        TextView genre = (TextView) view
                .findViewById(R.id.textViewMovieGenre);
        TextView runtime = (TextView) view
                .findViewById(R.id.textViewMovieRuntime);
        TextView rating = (TextView) view
                .findViewById(R.id.textViewMovieRating);
        TextView year = (TextView) view
                .findViewById(R.id.textViewMovieYear);
        ImageView setItemPoster = (ImageView) view
                .findViewById(R.id.imageViewItemPoster);

        name.setText(movieName);
        genre.setText("*" + movieGenre);
        runtime.setText("*" + movieRuntime);
        rating.setText("*" + "R:" + " " + movieRating);
        year.setText("*" + movieReleasedYear);


        /// get the poster to the item layout with universal image loader ////  
            DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheOnDisc()
            .cacheInMemory()
            .resetViewBeforeLoading()
            .build();


            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .threadPoolSize(3)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .memoryCacheSize(1500000)
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            .build();
            ImageLoader.getInstance().init(config);

            ImageLoader.getInstance().displayImage(itemPoster, setItemPoster, options);

        }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return getLayoutInflater().inflate(R.layout.movies_item_layout,
                parent, false);
    }



    }



// / on item click go to show only activity (editactivity is different
// activity)//////
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {

    Movie m = dbHandler.query(id);
    Intent intent = new Intent(this, MovieShowActivity.class);
    intent.setAction(Intent.ACTION_VIEW);
    intent.putExtra("name", m.getMovieName());
    intent.putExtra("plot", m.getMoviePlot());
    intent.putExtra("genre", m.getMovieGenre());
    intent.putExtra("director", m.getMovieDirector());
    intent.putExtra("cast", m.getMovieCast());
    intent.putExtra("trailer", m.getTrailerUrl());
    intent.putExtra("runtime", m.getMovieRuntime());
    intent.putExtra("year", m.getMovieReleasdYear());
    intent.putExtra("rating", m.getMovieRating());
    intent.putExtra("poster", m.getPosterUrl());

    startActivity(intent);

}

// / on back pressed dialog////
@Override
public void onBackPressed() {

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            switch (which) {
            case DialogInterface.BUTTON_POSITIVE:

                finish();
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                onResume();
                break;

            }
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    AlertDialog dialog = builder.setTitle("Wait!!!")
            .setMessage("Are You Sure You Want To Quit?")
            .setIcon(R.drawable.backpressedicon)
            .setPositiveButton("YES", listener)
            .setNegativeButton("NO", listener).create();
    dialog.show();
}

// / ondestroy - to stop the sound///
@Override
protected void onDestroy() {
    super.onDestroy();
    mp.stop();
}

@Override
public void onClick(View v) {

    switch (v.getId()) {
    case R.id.imageViewAddMovie:

        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                switch (which) {
                ///open activity to add new movie////
                case DialogInterface.BUTTON_POSITIVE:
                    Intent intent = new Intent(MainActivity.this,
                            AddMovieManually.class);
                    intent.setAction(Intent.ACTION_INSERT);
                    startActivity(intent);

                    break;

                case DialogInterface.BUTTON_NEUTRAL:
                    onResume();

                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    Intent byInternet = new Intent(MainActivity.this, 
                            AddMovieByInternet.class);
                    byInternet.setAction(Intent.ACTION_INSERT);
                    startActivity(byInternet);

                    break;

                }
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog dialog = builder
                .setMessage("How Do You Want To Add The Movie?")
                .setPositiveButton("Manually", listener)
                .setNeutralButton("Cancel", listener)
                .setNegativeButton("By The Intenet", listener).create();
        dialog.show();

        break;
    }

}

}

0 个答案:

没有答案