Issue in setting Textview's text in Custom Adapter for Android

孤者浪人 提交于 2019-12-07 16:21:38

问题


I am not able to set textview's setText property inside getView() method of Custom Adapter.

I already tried below solutions but it does not work for me :

  • Solution One
  • Solution Two
  • Solution Three

Listview.xml file :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imgLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:divider="@null"
    android:dividerHeight="5dp"
    android:scrollbars="none" />

</RelativeLayout>

Below is my keep_resing xml file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customRowLayout"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_marginTop="20dp"
android:orientation="horizontal" >

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/Btn"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/thumb_down_disabled" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="@string/resing"
            android:textColor="#357EC7"
            android:textSize="10sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/lyricsTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />

        <RelativeLayout
            android:id="@+id/parentLayout"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="5dp"
            android:background="@drawable/playing_view"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/helloTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_marginLeft="5dp"
                android:singleLine="true"
                android:text="Hello"
                android:textColor="#357EC7"
                android:textSize="14sp" />

            <ImageView
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="5dp"
                android:background="@drawable/volume" />
        </RelativeLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/keepBtn"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginRight="10dp"
            android:background="@drawable/thumb_up_disabled" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="@string/keep"
            android:textColor="#357EC7"
            android:textSize="10sp" />
    </LinearLayout>
</RelativeLayout>

Below is my adapter code :

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.stream.Position;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Handler;
import android.os.PowerManager;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class KeepReSingAdapter extends BaseAdapter implements OnClickListener {

    /*********** Declare Used Variables *********/
    private Activity activity;
    private ArrayList data;
    private static LayoutInflater inflater = null;
    public Resources res;
    SongCue tempValues = null;
    int i = 0;

    private ArrayList<SongCue> songCue;
    private int cueIndex = 0;
    private String selectedSongId;
    private MediaPlayer mMediaPlayer;
    ViewHolder holder;
    View vi;
    boolean right_button_flag, left_button_flag;
    SessionManager session;

    // int left_button_flag;

    /************* CustomAdapter Constructor *****************/
    public KeepReSingAdapter(Activity a, ArrayList d, Resources resLocal) {

        /********** Take passed values **********/
        activity = a;
        data = d;
        res = resLocal;

        /*********** Layout inflator to call external xml layout () ***********/
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);



        selectedSongId = SessionManager.getInstance(
                activity.getApplicationContext()).getString(
                AppConstants.SONG_ID);

        right_button_flag = false;
        left_button_flag = false;

        // Session class instance
        session = new SessionManager(activity.getApplicationContext());

    }

    /******** What is the size of Passed Arraylist Size ************/
    public int getCount() {

        if (data.size() <= 0)
            return 1;
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

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

    /********* Create a holder Class to contain inflated xml file elements *********/
    public static class ViewHolder {

        public TextView lyricsTxt, helloTxt;
        // public TextView text1;
        public ImageButton leftBtn, rightBtn;
        public RelativeLayout parentLayout;
        public LinearLayout rowLayout;

        // public TextView textWide;
        // ImageView image;

    }

    /****** Depends upon data size called for each row , Create each ListView row *****/
    public View getView(final int position, View convertView, ViewGroup parent) {

        vi = convertView;

        if (convertView == null) {

            vi = inflater.inflate(R.layout.keep_resing, null);

            holder = new ViewHolder();
            holder.lyricsTxt = (TextView) vi.findViewById(R.id.lyricsTxt);
            holder.helloTxt = (TextView) vi.findViewById(R.id.helloTxt);

            holder.leftBtn = (ImageButton) vi.findViewById(R.id.reSingBtn);
            holder.rightBtn = (ImageButton) vi.findViewById(R.id.keepBtn);
            holder.parentLayout = (RelativeLayout) vi
                    .findViewById(R.id.parentLayout);
            holder.rowLayout = (LinearLayout) vi
                    .findViewById(R.id.customRowLayout);





            vi.setTag(holder);

        } else {
            holder = (ViewHolder) vi.getTag();

        }

        if (data.size() <= 0) {



        } else {
            /***** Get each Model object from Arraylist ********/
            tempValues = null;
            tempValues = (SongCue) data.get(position);


            holder.lyricsTxt.setText(tempValues.getLyric());

            List<Song> AllSong = SplashScreen_Activity.songs;
            if (selectedSongId != null) {
                for (Song tempsong : AllSong) {
                    if (tempsong.songId.equals(selectedSongId)) {
                        songCue = (ArrayList<SongCue>) tempsong.songCues.songCue;
                    }
                }
            } else {

            }




            holder.parentLayout.setOnClickListener(new View.OnClickListener() {

               @Override
               public void onClick(View v) {

                Toast.makeText(activity.getApplicationContext(),
                        " " + position, Toast.LENGTH_SHORT).show();

                     holder.helloTxt.setText("Test");

                    Toast.makeText(activity.getApplicationContext(),
                            holder.helloTxt.getText().toString(),
                            Toast.LENGTH_LONG).show();


                   }
               });



        }
        vi.setOnClickListener(new OnItemClickListener(position));
        return vi;
    }


    @Override
    public void onClick(View v) {
        Log.v("CustomAdapter", "=====Row button clicked=====");

    }

    /********* Called when Item click in ListView ************/
    private class OnItemClickListener implements OnClickListener {
        private int mPosition;

        OnItemClickListener(int position) {
            mPosition = position;
        }

        @Override
        public void onClick(View arg0) {


        }
    }

}

Problem is, I am not able to change the text view text to "Test".

Note : If I see the value in Toast by doing "holder.helloTxt.getText().toString()" it shows me "Test".

I don't know why this problem is arising.Any help will be highly appreciated.

Thanks


回答1:


Finally I got the solution to my question and guess what it was a minor updation in the code.

I updated my code to :

final ViewHolder holder; 

inside getView() of CustomAdapter instead of declaring it globally.

Once again, thanking you all for your answers.

It helped me to look into my code in detail.




回答2:


Try this hope this helps

    vi = convertView;
    if (vi == null) {
        vi = inflater.inflate(R.layout.xmlfile, null);
        holder = new ViewHolder();
        holder.helloTxt= (TextView) vi.findViewById(R.id.hearTxt);
        holder.parentLayout= (RelativeLayout) vi
                .findViewById(R.id.parentLayout);

        vi.setTag(holder);
    }else
        holder=(ViewHolder)vi.getTag();

        holder.parentLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(activity.getApplicationContext(),
                        " " + position, Toast.LENGTH_SHORT).show();

                     holder.helloTxt.setText("Test");// not required
                    // just change the value of text in your list(which you are passing to the adapter) at corresponding position and then notify the list
                     notifyDataSetChanged();

                    Toast.makeText(activity.getApplicationContext(),
                            holder.helloTxt.getText().toString(),
                            Toast.LENGTH_LONG).show();


            }
        });

       return vi;

It will display the text "test" but when you scroll, it will again changed to its original value so you have to change the value in the list also which you are sending to the adapter

Also in your case the problem is, when you update the text of your TextView, it gets updated for the time being that's why you are getting the TextView text in your Toast. But in order to show the updated text in ListView, you have to notify the List. But when you do so, your TextView resets to original value. So all you have to do is to take a global String variable and intialise that to your initial value whatever you want like this

private String yourText="initial text"

and in getView() set your TextView text to this variable like this

holder.helloTxt.setText(yourText);

and when you click your parentLayout,just assign, this string the value you want and notify the list

yourText="test";
notifyDataSetChanged();

and this will do the trick. But remember this works only when you have single row, if you have multiple rows you have to take a String array.




回答3:


Do you perform a holder = vi.getTag(); in case the convertView not is null? This is necessary when a view is already created to reinitialise it in the state it was.




回答4:


Problem is, I am not able to change the text view text to "Test".

you are doing it wrong. Let's say your adapter is made of String. What I would have expected, is

 if (convertView == null) {
   // inflate stuff 
   // create older
   // set the older in the converView's tag
  } else {
   // retriewholder
  }
  // here you set the String in the holder at position:
  String tmpString = getItem(position);
  holder.helloTxt.setText(tmpString);
  holder.parentLayout.setTag(position);

Inside the onClick, you can retrieve the position trough the tag object, and update the String in the dataset and call notifyDataSetChanged




回答5:


Your problem is you didnot touch the parent layout. Make sure that your finger can touch the parentLayout, you can add padding for it. Or you can try

holder.helloTxt.setOnClickListener(...)

instead of parentLayout.




回答6:


I've seen a lot of ways but for me the simple way is pass component view to adapter. Then you can change you need. See an example below:

Link



来源:https://stackoverflow.com/questions/26800762/issue-in-setting-textviews-text-in-custom-adapter-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!