列表视图中单击的项目位置错误

时间:2019-06-02 16:21:24

标签: java android listview

我是android studio编程的新手,尝试从列表片段中单击列表视图中某个项目的位置时遇到麻烦。

问题是,我有一个主要活动,其中有一个查看寻呼机,而其中一个页面是歌曲列表。我想要的是获取此列表中所选歌曲的位置。我尝试在mi List片段中实现单击处理程序,但它始终向我显示下一个错误:“在父级或祖先上下文中找不到方法”(已经尝试更改函数名称和xml文件中的名称),所以我尝试了在MainActivity中处理click事件,它实际上可以正常工作,但是当我尝试获取位置时,它始终使我返回-1

这些是与我相关的文件: MainActivity.java

package com.example.marino.practica2marinoperezsegura;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ListFragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity  implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener  {
    private static final int REQ_PERMISSION = 1543;
    private boolean changeTheme = false;
    private ArrayList<Uri> paths = new ArrayList<Uri>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQ_PERMISSION);
            return;
        }

        SQLiteOpenHelper songDbHelper = new SongsDataHelper(this) ;
        SQLiteDatabase db = songDbHelper.getReadableDatabase();

        Cursor path = db.query("SONGS",
                new String[] {"PATH"},
                null,
                null,
                null, null, null);

        if (path.moveToFirst()) {
            do {
                paths.add(Uri.parse(path.getString(0)));
            } while(path.moveToNext());
        }

        SharedPref sharedPref;
        sharedPref = new SharedPref(this);
        if(sharedPref.loadNightModeState() == true){
            changeTheme = true;
            setTheme(R.style.SecondActivityTheme);
        }
        else {
            setTheme(R.style.AppTheme);
        }


        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        CategoriesPagerAdapter adapter = new CategoriesPagerAdapter(
                getSupportFragmentManager(), this);
        ViewPager pager = findViewById(R.id.viewpager);
        pager.setAdapter(adapter);

        android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(pager);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayoutMain);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                0,
                0
        );
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.navigationdrawer_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed()
    {
        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayoutMain);
        if (drawerLayout.isDrawerOpen(GravityCompat.START))
        {
            drawerLayout.closeDrawer(GravityCompat.START);
        }
        else
        {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();
        switch (id)
        {
            case R.id.navigation_lists :
                Intent lists = new Intent(this, ReproductionListActivity.class);
                startActivity(lists);
                break;
            case R.id.navigation_library :
                Intent library = new Intent(this, MainActivity.class);
                startActivity(library);
                break;
            case R.id.navigation_options :
                Intent options = new Intent(this, OptionsActivity.class);
                startActivity(options);
                break;
        }
        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayoutMain);
        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    //Here is where the event works but the int i gets always -1 value
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_song: {
                View parentRow = (View) v.getParent().getParent().getParent();
                ListView listView = (ListView) parentRow.getParent();
                if (!MediaPlayerManager.isInitialized()) {  //Never used media player? select file to play
                    try {
                        int i = listView.getSelectedItemPosition();
                        MediaPlayerManager.startNewTrack(this, paths.get(i));
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (MediaPlayerManager.isPlaying()) {
                    MediaPlayerManager.pauseMusic();
                } else {
                    MediaPlayerManager.startPlaying();
                }
                break;
            }
        }
    }


}

Songs.java

package com.example.marino.practica2marinoperezsegura;

import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import java.util.ArrayList;

public class Songs extends ListFragment{
    private boolean played = false;
    private ArrayList<Uri> paths = new ArrayList<Uri>();

    public Songs() {
// Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        SQLiteOpenHelper songDbHelper = new SongsDataHelper(getContext()) ;
        SQLiteDatabase db = songDbHelper.getReadableDatabase();
        //((SongsDataHelper) songDbHelper).addVideogame(db, "Pruebita","AJARL");
        Cursor path = db.query("SONGS",
                new String[] {"PATH"},
                null,
                null,
                null, null, null);

        /*if (path.moveToFirst()) {
            do {
                paths.add((path.get(0));
            } while(path.moveToNext());
        }*/

        Cursor cursor = db.query("SONGS",
                new String[] {"_id", "NAME", "DURATION"},
                null,
                null,
                null, null, null);

        String[] columns = new String[]{"NAME", "DURATION"};
        int[] to = new int[] {R.id.song_title, R.id.song_duration};


        SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(
                getContext(),
                R.layout.songs_list,
                cursor,
                columns,
                to,
                0);
        setListAdapter(listAdapter);
// Inflate the layout for this fragment
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public void onListItemclick(ListView l, View view, int position, long id){
        ViewGroup viewGroup= (ViewGroup)view;
        ImageButton selectedSong = (ImageButton)viewGroup.findViewById(R.id.play_song);
        Log.e("Name :" + position, " Album :");

    }

  //Here is where it shows me the "Could not find method in parent ancestor context" error

 /* @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_song: {
                Log.e("Name :", " Album :");
                break;
                if (!MediaPlayerManager.isInitialized()) {  //Never used media player? select file to play
                    MediaPlayerManager.startNewTrack(this, paths.get(0));
                } else if (this.played) {
                    MediaPlayerManager.pauseMusic();
                } else {
                    MediaPlayerManager.startPlaying();
                }
                break;
            }
        }
    }*/
}

CategoriesPageradapter.java

package com.example.marino.practica2marinoperezsegura;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class CategoriesPagerAdapter  extends FragmentPagerAdapter {
    private Context m_context;
    public CategoriesPagerAdapter (FragmentManager fragmentManager, Context context)
    {
        super(fragmentManager);
        m_context = context;
    }
    @Override
    public int getCount ()
    {
        return 2;
    }

    @Override
    public Fragment getItem (int position)
    {
        switch (position)
        {
            case 0:
                return new Albums();
            case 1:
                return new Songs();
        }
        return null;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position)
        {
            case 0:
                return m_context.getResources().getText(R.string.home_tab);
            case 1:
                return m_context.getResources().getText(R.string.songs_tab);
        }
        return null;
    }

}

我在这段代码中期望得到的是获取所选项目的位置数量并将其保存在i变量中,而不是得到-1

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

根据您的代码,您正在检查“活动”上的点击事件。如果我假设您在onClick()内获得了点击事件,

然后,您可以通过添加位置元数据来查看问题,以解决问题。喜欢

case R.id.play_song:
                    int position = (int)view.getTag();
                    //and use this position for MediaPlayer

现在如何设置这些元数据以进行查看。

为此,您需要通过扩展它来创建自己的版本的SimpleCursorAdapter类 像下面一样

public class MyAdapter extends SimpleCursorAdapter {

    public MyAdapter(Context context, int layout, Cursor c, String[] from,
                           int[] to, int flags) {
       super(context, layout, c, from,to,flags);
    }

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
       View view = super.getView(position, convertView, parent);
       //Here we are adding meta data which is position in our case
       view.findViewById(R.id.play_song).setTag(position);
       return view;
    }
}

现在在您的Songs片段中使用SimpleCursorAdapter的扩展版本。