2016-03-02 3 views
0

Я новичок в программировании на андроид и наблюдаю за видеороликами YouTube за последние 3 месяца, пытаясь научиться методом проб и ошибок. Я застрял.Как отобразить ArrayList в TextView при нажатии кнопки?

Все, что я пытаюсь сделать, это показать мой «JokeList.java» в TextView (robotJoke) после нажатия кнопки на экране. Может кто-нибудь, пожалуйста, помогите мне?

Вот мой файл MainActivity.java

package com.example.wdoty.comedianrobot; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
import java.lang.String; 
import java.util.ArrayList; 

public class MainActivity extends Activity{ 

ArrayList<String> jokeList; 
TextView robotJoke; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    robotJoke = (TextView) findViewById(R.id.robotJoke); 

} 

public void buttonClicked(){ 
    printJoke(); 
} 

public void printJoke(){ 
    String jokeString = jokeList.toString(); 
    robotJoke.setText(jokeString); 
} 


} 

Вот мой ArrayList.java (JokeList.java)

package com.example.wdoty.comedianrobot; 
import java.util.*; 



public class JokeList extends MainActivity{ 

public void jokes(){ 

    ArrayList<String> jokeList = new ArrayList<String>(); 

    jokeList.add("Why couldn't the bicycle stand up?"+ 
      "Because it was two tired"); 
    jokeList.add("What do you call a cheese that isn't yours?"+ 
      "Nacho Cheese!"); 
    jokeList.add("Before I criticize a man, I like to walk a mile in his shoes."+ 
      "That way, when I do criticize him, I'm a mile away and I have his shoes."); 
    jokeList.add("What do you call a fish with no eye?"+ 
      "Fssshh"); 
    jokeList.add("Have you heard the one about the Corduroy pillow?"+ 
      "It's making HEADLINES!"); 
    jokeList.add("What's red and bad for your teeth?"+ 
      "A brick."); 
    jokeList.add("Why didn't the melons get married?"+ 
      "Because they cantaloupe!"); 
    jokeList.add("What did the cobbler say when a cat wandered into his shop?"+ 
      "Shoe!"); 
    jokeList.add("What did the Buddhist say to the hot dog vendor?"+ 
      "Make me one with everything!"); 
    jokeList.add("The face of a child can say it all"+ 
      "especially the mouth part of the face."); 
    jokeList.add("Why did the cookie go to the hospital?"+ 
      "Because he felt crummy."); 
    jokeList.add("I intend to live forever..."+ 
      "So far, so good."); 

} 

} 

Вот мой activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity"> 

<ImageView 
    android:layout_width="120dp" 
    android:layout_height="120dp" 
    android:id="@+id/imageView" 
    android:src="@drawable/android" 
    android:layout_centerHorizontal="true"/> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/robotText" 
    android:text="Hello. My name is Andy the Android I like telling jokes. Click the button below if you would like for me to tell you 1." 
    android:layout_below="@+id/imageView" 
    android:paddingTop="10dp" /> 
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/button" 
    android:layout_below="@id/robotText" 
    android:paddingTop="15dp" 
    android:text="Button" 
    android:layout_centerHorizontal="true" 
    android:onClick="buttonClicked" /> 
<TextView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/robotJoke" 
    android:layout_below="@id/button" 
    android:paddingTop="30dp"/> 

</RelativeLayout> 
+0

и ButtonClick заменить этим общественного ничтожной buttonClicked (View V) { делать все, что вы хотите } –

+0

Класс Jokelist - это не активность, почему вы распространяетесь на MainActivity –

+0

Я получаю то, что вы пытаетесь сделать, дайте минутку. – Shark

ответ

0

You должен пересекать список и добавлять элементы списка один за другим.

public void printJoke(){ 
    StringBuilder jokeStringBuilder = new StringBuilder(); 
    for (String s : jokeList) { 
     jokeStringBuilder.append(s + "\n"); 
    } 
    robotJoke.setText(jokeStringBuilder.toString()); 
} 

Другая ошибка в том, что вы должны передать View в buttonClicked() функции быть buttonClicked(View v)

0

Сначала определите TextView, чем принимать все данные из ArrayList и установите TextView как в этом примере

TextView mText = (TextView) findViewById(R.id.yourtextviewid); 
for (int i=0; i<jokeList.size();i++) { 
    mText.setText(jokeList.get(i)); 
} 
-1

Протестируйте этот код:

package com.example.wdoty.comedianrobot; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
import java.lang.String; 
import java.util.ArrayList; 

public class MainActivity extends Activity{ 

ArrayList<String> jokeList; 
TextView robotJoke; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     robotJoke = (TextView) findViewById(R.id.robotJoke);  
    } 

    public void buttonClicked(View view){ 
     jokes(); 
     printJoke(); 
    } 

    public void printJoke(){   
     String jokeString = jokeList.toString(); 
     robotJoke.setText(jokeString); 
    } 

    public void jokes(){  
     jokeList = new ArrayList<String>();  
     jokeList.add("Why couldn't the bicycle stand up?"+ 
       "Because it was two tired"); 
     jokeList.add("What do you call a cheese that isn't yours?"+ 
       "Nacho Cheese!"); 
     jokeList.add("Before I criticize a man, I like to walk a mile in his shoes."+ 
       "That way, when I do criticize him, I'm a mile away and I have his shoes."); 
     jokeList.add("What do you call a fish with no eye?"+ 
       "Fssshh"); 
     jokeList.add("Have you heard the one about the Corduroy pillow?"+ 
       "It's making HEADLINES!"); 
     jokeList.add("What's red and bad for your teeth?"+ 
       "A brick."); 
     jokeList.add("Why didn't the melons get married?"+ 
       "Because they cantaloupe!"); 
     jokeList.add("What did the cobbler say when a cat wandered into his shop?"+ 
       "Shoe!"); 
     jokeList.add("What did the Buddhist say to the hot dog vendor?"+ 
       "Make me one with everything!"); 
     jokeList.add("The face of a child can say it all"+ 
       "especially the mouth part of the face."); 
     jokeList.add("Why did the cookie go to the hospital?"+ 
       "Because he felt crummy."); 
     jokeList.add("I intend to live forever..."+ 
       "So far, so good."); 
     String jokeString = jokeList.toString(); 
     Log.d("JOKES",jokeString);  
    } 
+0

Не будет работать, вы никогда не назначаете 'jokeList' – Shark

+0

см. Ответ с открытыми глазами, которые я вызывал, шутки функции. в этой функции arrayList готовит –

+0

А, пропустил, что это глобальная переменная, моя плохо. Тем не менее, он не будет печатать ни одной шутки - он будет больше похож на «[joke1Q? Joke1A», «joke2Q? Joke2A», «joke3Q? Joke3A», ...] 'вы, вероятно, хотите получить одну случайную шутку из списка и поместить это в текст. – Shark

0

Ваш JokeList не должен расширять MainActivity. Добавьте конструктор, чтобы заполнить ваш массив.

public class JokeList{ 
private ArrayList<String> jokeList; 
public JokeList(){ 

    jokeList = new ArrayList<String>(); 

    jokeList.add("Why couldn't the bicycle stand up?"+ 
      "Because it was two tired"); 
    jokeList.add("What do you call a cheese that isn't yours?"+ 
      "Nacho Cheese!"); 
    jokeList.add("Before I criticize a man, I like to walk a mile in his shoes."+ 
      "That way, when I do criticize him, I'm a mile away and I have his shoes."); 
    jokeList.add("What do you call a fish with no eye?"+ 
      "Fssshh"); 
    jokeList.add("Have you heard the one about the Corduroy pillow?"+ 
      "It's making HEADLINES!"); 
    jokeList.add("What's red and bad for your teeth?"+ 
      "A brick."); 
    jokeList.add("Why didn't the melons get married?"+ 
      "Because they cantaloupe!"); 
    jokeList.add("What did the cobbler say when a cat wandered into his shop?"+ 
      "Shoe!"); 
    jokeList.add("What did the Buddhist say to the hot dog vendor?"+ 
      "Make me one with everything!"); 
    jokeList.add("The face of a child can say it all"+ 
      "especially the mouth part of the face."); 
    jokeList.add("Why did the cookie go to the hospital?"+ 
      "Because he felt crummy."); 
    jokeList.add("I intend to live forever..."+ 
      "So far, so good."); 

} 
public ArrayList<String> jokes(){ 
    return jokeList; 
} 


} 

Ваша деятельность: Создать объект JokeList и задать ему ArrayList.

public class MainActivity extends Activity{ 

ArrayList<String> jokeList; 
JokeList myJokes; 
TextView robotJoke; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    robotJoke = (TextView) findViewById(R.id.robotJoke); 
    myJokes = new JokeList(); 

} 

public void buttonClicked(){ 
    printJoke(); 
} 

public void printJoke(){ 
    jokeList = myJokes.jokes(); 
    String jokeString = jokeList.toString(); 
    robotJoke.setText(jokeString); 
} 


} 
+0

Это тоже не должно быть класс, это всего лишь один метод. – Shark

+0

Возможно, он хочет позже создать другие методы. Но да, если ему просто нужно заполнить массив, метод в MainActivity - лучшее решение. –

+0

«Возможно, он хочет позже создать другие методы». - может быть, это должно быть указано в вопросе, так что класс шуток должен быть расширяемым. Но эй, это домашнее задание/приложение для хобби :) Человек сформирует мнение (и вкус) по этому вопросу, поскольку он привыкает к программированию. – Shark

0

Хорошо, что мы собираемся сделать это немного по-другому ...

package com.example.wdoty.comedianrobot; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
import java.lang.String; 
import java.util.ArrayList; 

public class MainActivity extends Activity{ 

ArrayList<String> jokeList; 
TextView robotJoke; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    robotJoke = (TextView) findViewById(R.id.robotJoke); 
    jokeList = jokes(); 
} 

public void buttonClicked(){ 
    printJoke(); 
} 

public void printJoke(){ 
    Random jokeNumber = new Random(); 
    String jokeString = jokeList.get(jokeNumber.nextInt() % jokeList.size()).toString(); 
    robotJoke.setText(jokeString); 
} 

public ArrayList<String> jokes(){ 

ArrayList<String> jokeList = new ArrayList<String>(); 

jokeList.add("Why couldn't the bicycle stand up?"+ 
     "Because it was two tired"); 
jokeList.add("What do you call a cheese that isn't yours?"+ 
     "Nacho Cheese!"); 
jokeList.add("Before I criticize a man, I like to walk a mile in his shoes."+ 
     "That way, when I do criticize him, I'm a mile away and I have his shoes."); 
jokeList.add("What do you call a fish with no eye?"+ 
     "Fssshh"); 
jokeList.add("Have you heard the one about the Corduroy pillow?"+ 
     "It's making HEADLINES!"); 
jokeList.add("What's red and bad for your teeth?"+ 
     "A brick."); 
jokeList.add("Why didn't the melons get married?"+ 
     "Because they cantaloupe!"); 
jokeList.add("What did the cobbler say when a cat wandered into his shop?"+ 
     "Shoe!"); 
jokeList.add("What did the Buddhist say to the hot dog vendor?"+ 
     "Make me one with everything!"); 
jokeList.add("The face of a child can say it all"+ 
     "especially the mouth part of the face."); 
jokeList.add("Why did the cookie go to the hospital?"+ 
     "Because he felt crummy."); 
jokeList.add("I intend to live forever..."+ 
     "So far, so good."); 

return jokeList; 
} 

} 
+0

Акула, когда я использовал ваш код, вызывает ошибку: «length» (не может разрешить метод) и возвращает «шутки» (не может разрешать шутки). Есть идеи? –

+0

Вы скопировали метод 'jokes()' из ответа? – Shark

+0

ouch, извините, просто заметили проблему ... 'jokes()' возвращал несуществующий список. Кроме того, 'jokeList' инициализируется в' onCreate() ', используя' jokeList = jokes(); 'так что все остальное должно отлично проверяться. – Shark

0
public class MainActivity extends Activity{ 

ArrayList<String> jokeList; 
TextView robotJoke; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    robotJoke = (TextView) findViewById(R.id.robotJoke); 

} 

public void buttonClicked(View v){ // Missing View paramter 
    printJoke(); 
} 

public void printJoke(){ 
//from @Ahmed Hegazy 
    StringBuilder jokeStringBuilder = new StringBuilder(); 
    for (String s : jokeList) { 
     jokeStringBuilder.append(s + "\n"); 
    } 
    robotJoke.setText(jokeStringBuilder.toString()); 
} 


} 
Смежные вопросы