Как преобразовать ImageView в TextView?

Ниже мой класс WordAdapter

public class WordAdapter extends ArrayAdapter<Word>  {

/** Resource ID for the background color for this list of words */
private int mColorResourceId;

/**
 * Create a new {@link WordAdapter} object.
 *
 * @param context is the current context (i.e. Activity) that the adapter is being created in.
 * @param words is the list of {@link Word}s to be displayed.
 * @param colorResourceId is the resource ID for the background color for this list of words
 */
public WordAdapter(Context context, ArrayList<Word> words, int colorResourceId) {
    super(context, 0, words);
    mColorResourceId = colorResourceId;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if an existing view is being reused, otherwise inflate the view
    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
    final Word currentWord = getItem(position);

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

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

    // Find the ImageView in the list_item.xml layout with the ID image.
   final ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
    // Check if an image is provided for this word or not
    if (currentWord.hasImage()) {
        // If an image is available, display the provided image based on the resource ID
        imageView.setImageResource(currentWord.getImageResourceId());
        // Make sure the view is visible
        imageView.setVisibility(View.VISIBLE);
    } else {
        // Otherwise hide the ImageView (set visibility to GONE)
        imageView.setVisibility(View.GONE);
    }

    // Set the theme color for the list item
    View textContainer = listItemView.findViewById(R.id.text_container);
    // Find the color that the resource ID maps to
    int color = ContextCompat.getColor(getContext(), mColorResourceId);
    // Set the background color of the text container View
    textContainer.setBackgroundColor(color);

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

    // ImageView imageView = (ImageView) listItemView.findViewById(R.id.list_item);
    imageView.setTag(new Integer(position));
    imageView.setOnClickListener(new ImageView.OnClickListener() {


       // Boolean flag = false;
       @Override
        public void onClick(View view) {
           // Toast.makeText(getContext(), "ImageView clicked for the row = " + view.getTag().toString(), Toast.LENGTH_SHORT).show();
          //  if ((Integer) view.getTag() == 0) {
          //      if (flag) {

             //       ((ImageView) view).setImageResource(R.string.miwok_letter_a);
                //    flag = false;
             //   } else {
              //      ((ImageView) view).setImageResource(R.drawable.ka_se_kamal);
             //       flag = true;
              // }
        //    }

        }

    });


    return listItemView;
}
}

и это мой класс Word

public class Word {

/** String resource ID for the default translation of the word */
private int mDefaultTranslationId;

/** String resource ID for the Miwok translation of the word */
private int mMiwokTranslationId;

/** Audio resource ID for the word */
private int mAudioResourceId;

/** Image resource ID for the word */
private int mImageResourceId = NO_IMAGE_PROVIDED;

/** Constant value that represents no image was provided for this word */
private static final int NO_IMAGE_PROVIDED = -1;

/**
 * Create a new Word object.
 *
 * @param defaultTranslationId is the string resource ID for the word in a language that the
 *                             user is already familiar with (such as English)
 * @param miwokTranslationId is the string resource Id for the word in the Miwok language
 * @param audioResourceId is the resource ID for the audio file associated with this word
 */
public Word(int defaultTranslationId, int miwokTranslationId, int audioResourceId) {
    mDefaultTranslationId = defaultTranslationId;
    mMiwokTranslationId = miwokTranslationId;
    mAudioResourceId = audioResourceId;
}

/**
 * Create a new Word object.
 *
 * @param defaultTranslationId is the string resource ID for the word in a language that the
 *                             user is already familiar with (such as English)
 * @param miwokTranslationId is the string resource Id for the word in the Miwok language
 * @param imageResourceId is the drawable resource ID for the image associated with the word
 * @param audioResourceId is the resource ID for the audio file associated with this word
 */
public Word(int defaultTranslationId, int miwokTranslationId, int imageResourceId,
            int audioResourceId) {
    mDefaultTranslationId = defaultTranslationId;
    mMiwokTranslationId = miwokTranslationId;
    mImageResourceId = imageResourceId;
    mAudioResourceId = audioResourceId;
}

/**
 * Get the string resource ID for the default translation of the word.
 */
public int getDefaultTranslationId() {
    return mDefaultTranslationId;
}

/**
 * Get the string resource ID for the Miwok translation of the word.
 */
public int getMiwokTranslationId() {
    return mMiwokTranslationId;
}

/**
 * Return the image resource ID of the word.
 */
public int getImageResourceId() {
    return mImageResourceId;
}

/**
 * Returns whether or not there is an image for this word.  */

public boolean hasImage() {
    return mImageResourceId != NO_IMAGE_PROVIDED;
}


/**
 * Return the audio resource ID of the word.
 */
public int getAudioResourceId() {
    return mAudioResourceId;
}
}

и ниже мой класс Fragmnent

public class VarnamalaConsonantsFragment extends Fragment {

/** Handles playback of all the sound files */
private MediaPlayer mMediaPlayer;

/** Handles audio focus when playing a sound file */
private AudioManager mAudioManager;



/**
 * This listener gets triggered whenever the audio focus changes
 * (i.e., we gain or lose audio focus because of another app or device).
 */
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
    @Override
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
            // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
            // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
            // our app is allowed to continue playing sound but at a lower volume. We'll treat
            // both cases the same way because our app is playing short sound files.

            // Pause playback and reset player to the start of the file. That way, we can
            // play the word from the beginning when we resume playback.
            mMediaPlayer.pause();
            mMediaPlayer.seekTo(0);
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
            mMediaPlayer.start();
        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            // The AUDIOFOCUS_LOSS case means we've lost audio focus and
            // Stop playback and clean up resources
            releaseMediaPlayer();
        }
    }
};




/**
 * This listener gets triggered when the {@link MediaPlayer} has completed
 * playing the audio file.
 */
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        // Now that the sound file has finished playing, release the media player resources.
        releaseMediaPlayer();
    }
};

public VarnamalaConsonantsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.word_list, container, false);

    // Create and setup the {@link AudioManager} to request audio focus
    mAudioManager = (AudioManager) getActivity().getSystemService(AUDIO_SERVICE);

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();

/** THIS IS THE LIST VIEW WHERE I NEED THE IMAGE (R.DRAWABLE.ka_se_kamal) 
WHEN CLICKED SHOULD BE CHANGED TO (R.STRING.miwok_letter_a) */


    words.add(new Word(R.string.letter_ka, R.string.miwok_letter_ka,
            R.drawable.ka_se_kamal, R.raw.ka_se_kamal_audio));
    words.add(new Word(R.string.letter_kha, R.string.miwok_letter_kha,
            R.drawable.kha_se_kharghosh, R.raw.kha_se_khargosh_audio));
    words.add(new Word(R.string.letter_ga, R.string.miwok_letter_ga,
            R.drawable.ga_se_gamla, R.raw.ga_se_gamla_audio));
    words.add(new Word(R.string.letter_gha, R.string.miwok_letter_gha,
            R.drawable.gha_se_ghar, R.raw.gh_se_ghar_audio));
    words.add(new Word(R.string.letter_nga, R.string.miwok_letter_nga,
            R.drawable.dya_se_dya, R.raw.ada_audio));


    // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
    // adapter knows how to create list items for each item in the list.
    WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_numbers);

    // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
    // There should be a {@link ListView} with the view ID called list, which is declared in the
    // word_list.xml layout file.
    ListView listView = (ListView) rootView.findViewById(R.id.list);

    // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
    // {@link ListView} will display list items for each {@link Word} in the list.
    listView.setAdapter(adapter);

    // Set a click listener to play the audio when the list item is clicked on
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Request audio focus so in order to play the audio file. The app needs to play a
            // short audio file, so we will request audio focus with a short amount of time
            // with AUDIOFOCUS_GAIN_TRANSIENT.
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
                    AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // We have audio focus now.

                // Create and setup the {@link MediaPlayer} for the audio resource associated
                // with the current word
                mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId());

                // Start the audio file
                mMediaPlayer.start();

                // Setup a listener on the media player, so that we can stop and release the
                // media player once the sound has finished playing.
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });

    return rootView;
}

@Override
public void onStop() {
    super.onStop();

    // When the activity is stopped, release the media player resources because we won't
    // be playing any more sounds.
    releaseMediaPlayer();
}

/**
 * Clean up the media player by releasing its resources.
 */
private void releaseMediaPlayer() {
    // If the media player is not null, then it may be currently playing a sound.
    if (mMediaPlayer != null) {
        // Regardless of the current state of the media player, release its resources
        // because we no longer need it.
        mMediaPlayer.release();

        // Set the media player back to null. For our code, we've decided that
        // setting the media player to null is an easy way to tell that the media player
        // is not configured to play an audio file at the moment.
        mMediaPlayer = null;

        // Regardless of whether or not we were granted audio focus, abandon it. This also
        // unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
        mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
    }
}

}

Мне нужно преобразовать мой ImageView в TextView, чтобы я мог переключать изображение в моем ListView на текст при его нажатии. Как преобразовать ImageView в TextView?

ВИД СПИСКА, ГДЕ МНЕ НУЖНО ИЗОБРАЖЕНИЕ (R.DRAWABLE.ka_se_kamal), ПРИ НАЖАТИИ ДОЛЖЕН БЫТЬ ИЗМЕНЕН НА (R.STRING.miwok_letter_a)

Причина, по которой другие вопросы не решили мою проблему, заключается в том, что все решения позволяют изменить представление изображения через setBackgroundResource, где изображение можно изменить в списке при нажатии. но для этого мне нужно создать изображения для всех элементов в списке, которые могут быть тяжелыми для ресурсов.. если изображение в списке можно изменить на текстовое представление, было бы намного лучше..


person amit    schedule 11.06.2018    source источник
comment
Пожалуйста, предоставьте код, чтобы люди могли лучше помочь вам. Также, если вы видели похожие вопросы - объясните, почему они не отвечают на ваш собственный вопрос.   -  person chevybow    schedule 11.06.2018
comment
@chevybow отредактировал вопрос, чтобы показать полный код... предложите подходящее решение   -  person amit    schedule 12.06.2018


Ответы (1)


Вы должны использовать как imageView, так и textView. Вы можете изменить видимость. Когда пользователь щелкает imageView, вы можете отключить его видимость и установить видимость textView как видимую. Вот код, который работал у меня:

       Boolean flag =false;
         @Override
        public void onClick(View view) {

               // Toast.makeText(getContext(), "ImageView clicked for the row = "+view.getTag().toString(), Toast.LENGTH_SHORT).show();
            if(flag){

                imageView.setAlpha(255);
               // imageView.setImageResource(R.drawable.a_se_anaar);
                onClickTextView.setVisibility(View.INVISIBLE);
                flag = false;
            }else{
                imageView.setAlpha(0);
                onClickTextView.setVisibility(View.VISIBLE);
                flag =true;

            }

        }
person Raj    schedule 11.06.2018
comment
Я хочу изменить изображение в списке, которое находится в ArrayAdapter.. и все изображения в списке должны быть видны до тех пор, пока действие не будет запущено.. Я хочу, чтобы изображение, которое щелкнули, было изменено на текст.. не затрагивая другие изображения списка.. - person amit; 11.06.2018
comment
Где код для замены ImageView на TextView? @Радж - person amit; 12.06.2018
comment
по этой ссылке ..stackoverflow.com/questions/5274145/.. возможно ли написать код, подобный этому.. для TextView тоже... ImageView iv = new ImageView(getBaseContext()); iv.setBackgroundResource(R.drawable.redbg); Drawable d = iv.getBackground(); d.setBounds(0, 0, 50, 50); tv3.setCompoundDrawables(d, null, null, null); - person amit; 12.06.2018
comment
Я нашел решение. Проблема была в файле макета. Изменил линейный макет на относительный макет, чтобы наложить текст на изображение и переключить их при нажатии на изображение ... как было предложено @Raj ... спасибо!! - person amit; 12.06.2018