如何在listView程序的textView中附加音频文件?

时间:2018-10-13 08:26:05

标签: android listview

我创建了一个已经运行的应用程序,该应用程序显示ListView项,并且在选择列表中的项时,它会打开新活动。在new_activity内部,我有TextView和Image按钮,显示播放,暂停和停止的音频按钮。 TextView可以正常运行,但是图像按钮拒绝播放原始文件夹中的音频文件。我的原始文件夹中有很多音频文件,并希望将每个音频文件分配给将打开每个新活动的每个ListView。请帮我编辑下面的ListViewAdapter代码,以播放,暂停和停止播放每个音频文件。

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter{

    //Variables
    Context mContext;
    LayoutInflater inflater;
    List<Model> modellist;
    ArrayList<Model> arrayList;
    MediaPlayer Player;
    



    //Constructor
    public ListViewAdapter(Context context, List<Model> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Model>();
        this.arrayList.addAll(modellist);
    }

    public class ViewHolder{
        TextView mTitleTv, mDescTv;
        ImageView mIconTv;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.row, null);

            //locate the views in row.xml
            holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
            holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
            holder.mIconTv = view.findViewById(R.id.mainIcon);



            view.setTag(holder);
        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the result into textview
        holder.mTitleTv.setText(modellist.get(i).getTitle());
        holder.mDescTv.setText(modellist.get(i).getDesc());
        //Set the result in imagview
        holder.mIconTv.setImageResource(modellist.get(i).getIcon());

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //code later
                if (modellist.get(i).getTitle().equals("Item 1| information central for ANSPP")){
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent =  new Intent(mContext, NewActivity.class);
                    intent.putExtra("actionBarTitle", "Item 3");
                    intent.putExtra("contentTv", "This is the text for information central of all ANSPP");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Item 2| information central for ANSPP")){
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent =  new Intent(mContext, NewActivity.class);
                    intent.putExtra("actionBarTitle", "Item 3");
                    intent.putExtra("contentTv", "This is the text for information central of all ANSPP");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Item 3| information central for ANSPP")){
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent =  new Intent(mContext, NewActivity.class);
                    intent.putExtra("actionBarTitle", "Item 3");
                    intent.putExtra("contentTv", "This is the text for information central of all ANSPP");
                    mContext.startActivity(intent);
                }

            }
        });


        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (Model model : arrayList){
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }


}

新的Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_marginTop="5dp"
    tools:context=".NewActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Play Audio music →"
            android:layout_marginStart="10dp"
            android:textColor="#8c0b0b"
            android:layout_marginLeft="10dp" />
    </LinearLayout>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:onClick="play"
        android:layout_marginStart="140dp"
        android:src="@drawable/ic_play_circle_outline_black_24dp"

        android:layout_marginLeft="5dp" />

    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="145dp"
        android:onClick="pause"
        android:src="@drawable/ic_pause_circle_outline_black_24dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="145dp" />

    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="85dp"
        android:onClick="stop"
        android:src="@drawable/ic_stop_black_24dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="85dp" />

    <ScrollView
        android:layout_width="340dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView"
                android:layout_width="336dp"
                android:layout_height="fill_parent"
                android:enabled="true"
                android:focusable="true"
                android:fontFamily="sans-serif-condensed"
                android:text="Details later..."
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#000"
                android:textIsSelectable="true"
                android:textSize="21sp" />
        </LinearLayout>
    </ScrollView>
    
</RelativeLayout>


下面列出了NewActivity.java。此活动中的MediaPlayer在所有列表视图中播放一首歌曲。我想在ListViewAdapter.java中实现此代码,以便为每个ListView内容分配每个音频文件。谢谢

NewActivity.java

public class NewActivity extends AppCompatActivity {
    private String TAG = "NewActivity ----- ; " ;
    // Store instance variables
    private String title;
    private int page;
    MediaPlayer player;

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

        ActionBar actionBar = getSupportActionBar();
        TextView mDetailTv = findViewById(R.id.textView);


        //get data from previous activity when item of activity is clicked using intent
        Intent intent = getIntent();
        String mActionBarTitle = intent.getStringExtra("actionBarTitle");
        String mContent = intent.getStringExtra("contentTv");

        //setctionBar Title
        actionBar.setTitle(mActionBarTitle);
        //get text in text textView
        mDetailTv.setText(mContent);

        //ok we are done,




    public void  play(View v) {
        if (player == null) {
            player = MediaPlayer.create(this, R.raw.song_1);
            Toast.makeText(this, "Tune Playing", Toast.LENGTH_SHORT ).show();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlayer();
                }
            });
        }
        player.start();
    }
    public void pause(View v) {
        if (player != null) {
            player.pause();
            Toast.makeText(this, "Tune Paused", Toast.LENGTH_SHORT ).show();
        }
    }
    public void stop(View v) {
    stopPlayer();
    }
    private void stopPlayer() {
        if (player != null) {
            player.release();
            player = null;
            Toast.makeText(this, "Tune Stoped", Toast.LENGTH_SHORT ).show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPlayer();
    }

}

1 个答案:

答案 0 :(得分:0)

@Merinze

我将逐步解释如果我所有的音频文件都位于 res 文件夹下的 raw 文件夹中,该如何实现。

首先创建您的项目,然后按所需方式命名。进入项目文件夹并导航 app-> src-> main-> res ,然后在其中创建一个名为 raw 的新文件夹。将所有音频放在此处,并记住有一些有关资源命名的规则。

查看链接:Android resource naming convention

创建您的项目主要活动,您将在其中检索音频并将其列出在MainActivity的ListView中。

MainActivity的XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">


    <ListView
        android:id="@+id/list_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp" />
</android.support.design.widget.CoordinatorLayout>

MainActivity的JAVA:

public class MainActivity extends AppCompatActivity {
private ListView listView;
private ListAdapter listAdapter;
private List<AudioModel> audioModelList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       //instantiate the list object
        audioModelList=new ArrayList<>();

        listView=(ListView)findViewById(R.id.list_data);

        listAdapter = new ListAdapter(audioModelList,getApplicationContext());
        listView.setAdapter(listAdapter);


        /*retrieve raw files and add them to the list by calling this method declared at the end of class*/
        listRaw();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


   //define a method to fetch all files under your raw folder
    public void listRaw(){
        Field[] fields=R.raw.class.getFields();
        for(int count=0; count < fields.length; count++){
            Log.i("Raw Asset: ", fields[count].getName());

           /*create a new AudioModel object this is just a class name you can choose your own*/
            AudioModel audioModel=new AudioModel();
            audioModel.setName(fields[count].getName());


           //app the object to the list
            audioModelList.add(audioModel);
        }
        //notify the adapter
        listAdapter.notifyDataSetChanged();
    }
}

在AudioModel类文件下:

public class AudioModel {
    private String name,creationDate,singer;

    public AudioModel() {
    }

    public AudioModel(String name, String creationDate, String singer) {
        this.name = name;
        this.creationDate = creationDate;
        this.singer = singer;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(String creationDate) {
        this.creationDate = creationDate;
    }

    public String getSinger() {
        return singer;
    }

    public void setSinger(String singer) {
        this.singer = singer;
    }
}

为列表项创建新布局:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/audio"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="15dp">

</TextView>

创建一个列表适配器:

public class ListAdapter extends BaseAdapter {
    private List<AudioModel> audioModelList;
    private Context context;

    public ListAdapter(List<AudioModel> audioModelList, Context context) {
        this.audioModelList = audioModelList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return audioModelList!=null?audioModelList.size():0;
    }

    @Override
    public Object getItem(int position) {
        return audioModelList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView= LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);

        TextView audioName=(TextView)convertView.findViewById(R.id.audio);
        audioName.setText(audioModelList.get(position).getName());

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(v.getContext(),AudioModelPlayer.class).putExtra("actionBarTitle",audioModelList.get(position).getName()));
            }
        });
        return convertView;
    }
}

创建您的音频播放器课程:

public class AudioModelPlayer extends AppCompatActivity {
 private MediaPlayer mediaPlayer;
 private FloatingActionButton play,pause;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_model_player);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        play=(FloatingActionButton)findViewById(R.id.play);
        pause=(FloatingActionButton)findViewById(R.id.pause);

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer!=null)
                {
                    mediaPlayer.start();
                }
                pause.setVisibility(View.VISIBLE);
                play.setVisibility(View.GONE);
            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer!=null)
                {
                    mediaPlayer.pause();
                }
                play.setVisibility(View.VISIBLE);
                pause.setVisibility(View.GONE);
            }
        });

        mediaPlayer=new MediaPlayer();

        Intent intent=getIntent();

        if (intent!=null)
        {
            if (intent.hasExtra("actionBarTitle"))
            {
                setTitle(intent.getStringExtra("actionBarTitle"));


                   mediaPlayer=MediaPlayer.create(getApplicationContext(),getResources().getIdentifier(intent.getStringExtra("actionBarTitle"),"raw",getPackageName()));

            }
        }else
        {
            finish();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home)
        {
            if (mediaPlayer!=null)
            {
                if(mediaPlayer.isPlaying())
                {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }else
                {
                    mediaPlayer.release();
                }
            }
        }
        finish();
        return super.onOptionsItemSelected(item);
    }
}

这只是一个示例,您可以参考此文件来制作自己的应用程序,或者使其变得更好。此方法可用于位于其他任何地方的文件,但访问/读取文件的方式会有所不同。

您可以从GitHub AudioListProject

下载整个项目