如何在Recyclerview中点击该项目时显示该项目?

时间:2018-03-17 08:47:37

标签: android android-recyclerview

我将listview转换为recyclerview。当我运行代码并显示正常时,它工作。但是,我希望当我点击recyclerview上的某个项目时,它会返回该特定项目。我正在使用Toast消息来测试它。它不是返回该项,而是在Toast消息中显示“com.example.android.basicrecycle.Word@52809370”。如何显示该项目?

MainActivity.java

public class MainActivity extends AppCompatActivity implements WordAdapter.ListItemClickListener{
    private RecyclerView mRecyclerView;
    private WordAdapter mWordAdapter;

    //Create a Toast variable called mToast to store the current Toast
    private Toast mToast;

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

        //Database of words

        final ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("one", "uno"));
        words.add(new Word("two", "dos"));
        words.add(new Word("three", "tres"));
        words.add(new Word("four", "cuatro"));
        words.add(new Word("five", "cinco"));
        words.add(new Word("six", "seis"));
        words.add(new Word("seven", "siete"));
        words.add(new Word("eight", "ocho"));
        words.add(new Word("nine", "nueve"));
        words.add(new Word("ten", "diez"));
        words.add(new Word("eleven", "once"));
        words.add(new Word("twelve", "doce"));
        words.add(new Word("thirteen", "trece"));
        words.add(new Word("fourteen", "catorce"));
        words.add(new Word("fifteen", "quince"));

        mRecyclerView = (RecyclerView) findViewById(R.id.list);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        mRecyclerView.setLayoutManager(layoutManager);

        // Pass in this as the ListItemClickListener to the WordAdapter constructor
        mWordAdapter = new WordAdapter(words, this);
        mRecyclerView.setAdapter(mWordAdapter);

        //The "NextButton launches DetailActivity
        Button nextButton = (Button)findViewById(R.id.next_button);
        nextButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onListItemClick(ArrayList<Word> words, int i) {
        //In the beginning of the method, cancel the Toast if it isn't null
        if (mToast != null) {
            mToast.cancel();
        }

        //Show a Toast when an item is clicked, displaying that item number that was clicked
        String toastMessage = "Hello " + String.valueOf(words.get(i));
        mToast = Toast.makeText(this, toastMessage, Toast.LENGTH_LONG);

        mToast.show();
    }
}

Word.java

public class Word {
    /** Default translation for the word */
    private String mEnglishTranslation;

    /** Spanish translation for the word */
    private String mSpanishTranslation;

    /**
     * Create a new Word object.
     *
     * @param englishTranslation is the word in a language that the user is already familiar with
     *                           (such as English)
     * @param spanishTranslation is the word in the Spanish language
     */
    public Word(String englishTranslation, String spanishTranslation) {
        mEnglishTranslation = englishTranslation;
        mSpanishTranslation = spanishTranslation;
    }

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

    /**
     * Get the Spanish translation of the word.
     */
    public String getSpanishTranslation() {
        return mSpanishTranslation;
    }
}

WordAdapter.java

public class WordAdapter extends RecyclerView.Adapter <WordAdapter.ViewHolder>{
    //add An on-click handler that we've defined to make it easy for an Activity to interface with RecyclerView
    final private ListItemClickListener mOnClickListener;

    private ArrayList<Word> words;

    //Add an interface called ListItemClickListener. Within that interface, define a void method called onListItemClick that takes an int as a parameter
    public interface ListItemClickListener {
        void onListItemClick(ArrayList<Word> words, int i);
    }

    //Add a ListItemClickListener as a parameter to the constructor and store it in mOnClickListener
    public WordAdapter(ArrayList<Word> words, ListItemClickListener listener) {
        mOnClickListener = listener;
        this.words = words;
    }
    //Inflate an item view
    @Override
    public WordAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(WordAdapter.ViewHolder viewHolder, int i) {
        // Retrieve the data for that position
        viewHolder.mEnglish.setText( words.get(i).getEnglishTranslation());
        viewHolder.mSpanish.setText( words.get(i).getSpanishTranslation());
    }

    @Override
    public int getItemCount() {
        return words.size();
    }

    //Implement OnClickListener in the ViewHolder class
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView mEnglish;
        private TextView mSpanish;

        public ViewHolder(View view) {
            super(view);

            mEnglish = (TextView)view.findViewById(R.id.english_textview);

            mSpanish = (TextView)view.findViewById(R.id.spanish_textview);
            //Call setOnClickListener on the View passed into the constructor (use 'this' as the OnClickListener)
            view.setOnClickListener(this);
        }

        //Override onClick, passing the clicked item's position (getAdapterPosition()) to mOnClickListener via its onListItemClick method
        @Override
        public void onClick(View view) {
            int i = getAdapterPosition();
            mOnClickListener.onListItemClick(words, i);
        }
    }
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="7"
        android:background="#FFFFFF"
        xmlns:android="http://schemas.android.com/apk/res/android" />
    <Button
        android:id="@+id/next_button"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_gravity="center_horizontal"
        android:layout_weight="1"
        android:text="Next"/>
</LinearLayout>

list_item.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">
    <TextView
        android:id="@+id/english_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        tools:text="English" />
    <TextView
        android:id="@+id/spanish_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        tools:text="Spanish" />
</LinearLayout>

的build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.android.basicrecycle"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:recyclerview-v7:26.1.0'
}

logcat的

03-16 23:01:55.280 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: Hello: 0
03-16 23:01:55.280 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: com.example.android.basicrecycle.Word@52809280
03-16 23:17:29.828 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: Hello: 0
03-16 23:17:29.828 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: com.example.android.basicrecycle.Word@52809280
03-16 23:17:39.368 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: Hello: 3
03-16 23:17:39.368 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: com.example.android.basicrecycle.Word@52809370

1 个答案:

答案 0 :(得分:0)

你只需要调用obect,而不是值。删除 String.valueOf(...),不是必需的:

String toastMessage = "Hello " + words.get(i);

或使用:

Word word = words.get(i);
String toastMessage = "Hello " + word.getEnglishTranslation() 
                    + " - " + word.getSpanishTranslation();

您正试图展示整个对象。为了正确显示 Word 对象的内容,您还需要覆盖 toString()。类似的东西:

public class Word {

    ...

    @Override
    public String toString() {
        return "EnglishTranslation: " + mEnglishTranslation 
            + "\nSpanishTranslation: " + mSpanishTranslation; 
    }
}

我还建议你在支架内加入吐司,然后直接使用该物体。