gpt4 book ai didi

java - 在 ListView 中单击的项目位置错误

转载 作者:行者123 更新时间:2023-12-02 04:54:40 27 4
gpt4 key购买 nike

我是 android studio 编程的新手,在尝试从列表 fragment 获取 ListView 中单击的项目的位置时遇到了一些麻烦。

问题是,我有一个主要 Activity ,其中有一个查看寻呼机,其中一个页面是歌曲列表。我想要的是获取此列表中所选歌曲的位置。我尝试在 mi List fragment 中实现点击处理程序,但它总是显示下一个错误:“无法在父级或祖先上下文中找到方法”(已尝试更改函数的名称和 xml 文件中的名称),所以我尝试了处理 MainActivity 中的点击事件,它实际上有效,但是当我尝试获取位置时,它总是返回 -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;
}
}
}


}

歌曲.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;
}
}
}*/
}

类别Pageradapter.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

感谢您的宝贵时间。

最佳答案

根据您的代码,您正在检查“Activity ”上的点击事件。如果我假设您在 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 fragment 中使用 SimpleCursorAdapter 的扩展版本。

关于java - 在 ListView 中单击的项目位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416807/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com