Как использовать OnClickListener для настраиваемого массива с двумя текстами - PullRequest
0 голосов
/ 31 августа 2018

Я пытаюсь отправить OnClickListener в массив cusstom. Каждый элемент имеет 2 вида текста, но мне все равно, какой из них нажимается. Я просто хочу перейти к другому занятию с выбранным значением Musicclass, когда нажата строка списка (песня или исполнитель).

Вот основное занятие "Список":

public class MainActivity extends AppCompatActivity{

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

    ArrayList<Music> songs = new ArrayList<Music>();

    //words.add("one");
    songs.add(new Music("Under Pressure","Queen"));
    songs.add(new Music("My Way","Frank Sinatra"));
    songs.add(new Music("Stressed Out","21 Pilots"));
    songs.add(new Music("Despacito","Luis Fonzi"));
    songs.add(new Music("Shape of You","Ed Sheeran"));
    songs.add(new Music("Believer","Imagine Dragons"));


    MusicAdapter adapter = new MusicAdapter(this, songs);

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

    listView.setAdapter(adapter);


    // Set a click listener to go to the player activity

    listView.setOnClickListener(new AdapterView.OnClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Create a new intent to open the {@link NumbersActivity}

            Intent playerIntent = new Intent(MainActivity.this, Player.class);
            // Start the new activity
            startActivity(playerIntent);
        }
    });

}

}

после // Установить прослушиватель щелчков ..... // ничего не работает Я получаю ошибки, используя AdapterView, поэтому при необходимости не обращайте внимания на код после предыдущего комментария "//". playerintent начинает просто простое действие с текстового сообщения в будущем. Я хочу заполнить текстовое представление песней и именем исполнителя.

Это пользовательский адаптер:

public class MusicAdapter extends ArrayAdapter<Music>{

public MusicAdapter(Context context, ArrayList<Music> music) {
    super(context, 0, music);
}


public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }

    // Get the {@link Word} object located at this position in the list
    Music currentMusic = getItem(position);

    // Find the TextView in the list_item.xml layout with the ID miwok_text_view.
    TextView songTextView = (TextView) listItemView.findViewById(R.id.song_text_view);
    // Get the Miwok translation from the currentWord object and set this text on
    // the Miwok TextView.
    songTextView.setText(currentMusic.getSongTranslation());

    // Find the TextView in the list_item.xml layout with the ID default_text_view.
    TextView artistTextView = (TextView) listItemView.findViewById(R.id.artist_text_view);
    // Get the default translation from the currentWord object and set this text on
    // the default TextView.
    artistTextView.setText(currentMusic.getArtistTranslation());

    // Return the whole list item layout (containing 2 TextViews) so that it can be shown in
    // the ListView.
    return listItemView;
}

}

А это класс Музыка:

public class Music {


private String mSong;


private String mArtist;


public Music(String song, String artist) {
    mSong = song;
    mArtist = artist;
}

/**
 * Get the default translation of the word.
 */
public String getSongTranslation() {
    return mSong;
}

/**
 * Get the Miwok translation of the word.
 */
public String getArtistTranslation() {
    return mArtist;
}

}

Спасибо за любую помощь !!

1 Ответ

0 голосов
/ 31 августа 2018

Вы можете установить прослушиватель в представлении listItemView после if оператора

listItemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent playerIntent = new Intent(getContext(), Player.class);
            // Start the new activity
            getContext().startActivity(playerIntent);
        }
});
...