Звук начинается при нажатии элемента списка, как остановить?

Звук воспроизводится, когда пользователь выбирает элемент из списка, у меня есть три кнопки, одна из которых предназначена для остановки воспроизведения звука, а две другие - одна для воспроизведения следующего элемента в списке и одна для воспроизведения предыдущего

Как мне этого добиться? я сделал кнопки кликабельными, а затем я пытаюсь написать код, например. мп.стоп(); остановить музыку, но это не работает? а также как мне заставить другие кнопки воспроизводить следующие и предыдущие элементы в списке?

Ниже мой файл .java

public class Nasheeds extends ListActivity {
//ArrayList holds the data (as HashMaps) to load into the ListView
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
//SimpleAdapter does the work to load the data in to the ListView
private SimpleAdapter sa;





@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nasheeds2);



    //HashMap links each line of data to the correct TextView
    HashMap<String,String> item;
    for(int i=0;i<Nasheed.length;i++){
      item = new HashMap<String,String>();
      item.put( "line1", Nasheed[i][0]);
      item.put( "line2", Nasheed[i][1]);

      list.add( item );
    }

    sa = new SimpleAdapter(this, list,
            R.layout.nasheeds1,
            new String[] { "line1","line2" },
            new int[] {R.id.displayname, R.id.title});

    setListAdapter(sa);



  getListView().setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        switch (arg2)
        {
        case 0:
            System.out.println("User selected option 1");
             MediaPlayer mp = MediaPlayer.create(Nasheeds.this,         R.raw.mok);  
              mp.start(); 


            TextView tv=(TextView) findViewById(R.id.selectedfile);
            tv.setText("Playing "+ "Mountains of Mekkah, Zain Bikha");
            break;
        case 1:
            System.out.println("User selected option 2");

        case 2:

            break;                  
        }

    }

  });

}


private String[][] Nasheed =
    {{"Mountains of Mekkah","Zain Bikha"},
    {"Hadith 2","....add hadith...."},
    {"Hadith 3",".....add hadith"},};





}

и это мой один из файлов nasheed2.xml:

    <ListView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list"
        android:layout_weight="1.0"
        />

    <LinearLayout
            android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/screen_background_light"
    android:padding="10dip">

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/selectedfile"
            android:text="Not file selected"
            android:textColor="@android:color/black"
            android:gravity="center_horizontal"
            android:singleLine="true"
            android:ellipsize="middle"/>

    <SeekBar
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekbar"
            android:max="100"
            android:paddingBottom="10dip"/>

    <LinearLayout
                    android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:background="@android:drawable/screen_background_light">

        <TextView
            android:id="@+id/songCurrentDurationLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

            <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/prev"
                    android:src="@android:drawable/ic_media_previous"
                    android:onClick="doClick"/>

            <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/play"
                    android:src="@android:drawable/ic_media_play"
                    android:onClick="doClick"/>

            <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/next"
                    android:src="@android:drawable/ic_media_next"
                    android:onClick="doClick"/>

            <TextView
                android:id="@+id/songTotalDurationLabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />

    </LinearLayout> 
    </LinearLayout>

this is the other nasheed1.xml file:

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/displayname"
            android:textSize="18dip"
            android:textStyle="bold"
            android:singleLine="true"
            android:ellipsize="end"/>

    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/title"
                    android:textSize="15dip"
                    android:singleLine="true"
                    android:ellipsize="end"
                    android:layout_weight="1.0"/>

            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/duration"
                    android:gravity="right"
                    android:textSize="15dip"
                    android:singleLine="true"
                    android:ellipsize="end"/>
    </LinearLayout>

 </LinearLayout>

person Jay240692    schedule 06.12.2012    source источник


Ответы (1)


Попробуйте этот код ниже в событии клика play button.

public boolean istrue = true;

btnplay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (istrue) {
                    mp.pause();
                    istrue = false;
                } else {
                    mp.start();
                    istrue = true;
                }
            }
        });

или создайте еще одну кнопку для остановки звука.

при нажатии этой кнопки остановки используйте это

mp.stop();
person Arvind Kanjariya    schedule 07.12.2012
comment
извините, просто чтобы уточнить, следует ли использовать этот код внутри случая, когда запускается медиаплеер, или после public void onItemClick(AdapterView‹?> arg0, View arg1, int arg2, long arg3) { - person Jay240692; 07.12.2012
comment
да, после щелчка элемента при запуске медиаплеера и появлении экрана медиаплеера, чем на этом экране при нажатии кнопки, вы можете использовать этот код. - person Arvind Kanjariya; 07.12.2012
comment
Кажется, я не могу заставить его работать. он не распознает mp, потому что я создаю медиаплеер внутри случая onItemClick: 0? - person Jay240692; 07.12.2012
comment
Я предполагаю, что мне также нужно реализовать onclicklistener? - person Jay240692; 07.12.2012