#java #android #string #arraylist #random
#java #Android #строка #arraylist #Случайный
Вопрос:
Я пытаюсь разобраться с некоторыми материалами Android Java, и у меня возникли некоторые проблемы с обработкой всплывающего сообщения. Моя область позволяет отправлять случайное всплывающее сообщение из массива строк, который был вызван из другого ArrayList. Я выяснил, как распечатать их отдельно, хотя я чувствую, что с тех пор, возможно, мне многого не хватает, когда дело доходит до синтаксиса toast.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myListView = findViewById(R.id.myListView);
final ArrayList<String> myFamily = new ArrayList<>(asList("Giovani", "Enu", "Xochle", "Rquel", "Falsto", "Bam", "Duncan", "Goose", "Edgar", "Frank"));
ArrayList<String> gio = new ArrayList<>(asList(" His other brother ", " Met in high school ", " Played on the same sports team ", " Has two kids "));
ArrayList<String> karina = new ArrayList<>(asList(" His youngest sister ", " Kinda short ", " Sweet but kinda dumb "));
ArrayList<String> midget = new ArrayList<>(asList(" His Second youngest sister ", " Kinda short ", " Kinda a crazy cat lady ", " Cannot handle her liquor "));
ArrayList<String> ma = new ArrayList<>(asList(" His other mother ", " Works way too hard ", " Sweetest lady in the world "));
ArrayList<String> pa = new ArrayList<>(asList(" His other father ", " Not feeling well ", " Good heart hopefully he can live in peace "));
ArrayList<String> me = new ArrayList<>(asList(" The coolest ", " Kinda short ", " Sweet but kinda dumb "));
ArrayList<String> dunks = new ArrayList<>(asList(" Brother from another mother ", " Warrior born ", " Allergic to most things that could hinder combat "));
ArrayList<String> gus = new ArrayList<>(asList(" His other brother ", " Loves cars ", " Talks alot of shit ", " Loves white girls ", " Memorised the metal gear series by heart"));
ArrayList<String> edd = new ArrayList<>(asList(" Oldest of the other brother ", " Mostly quiet outside of social situations ", " Cares about saving his money ", " Laughs alot"));
ArrayList<String> frank = new ArrayList<>(asList(" Other brother ", " Impulsively stupid but loyal ", " Really into recreational passions "));
//ArrayList[] fList = new ArrayList[]{{myFamily.get(0),Bio.get()}, };
final Random chance = new Random();
final ArrayList<ArrayList> bio = new ArrayList (Arrays.asList(gio, karina, midget, ma, pa, me, dunks, gus, edd, frank));
//final int selectChance = chance.nextInt(bio.length);
/*
for (String selection : myFamily)
bio
return ;
}
*/
ArrayAdapter<String> arrayManager = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, myFamily);
myListView.setAdapter(arrayManager);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Sup " bio, Toast.LENGTH_LONG).show();
}
});
}
}
Комментарии:
1. Итак, у вас есть представление списка, которое содержит такие имена, как
Giovani
илиEnu
, и когда вы нажимаете на этот элемент, вы хотите отобразить случайное сообщение из списка, который содержит предложения для этого имени, например, дляGiovani
Вы хотите распечатать случайную строку изgio
? Я прав?2. @iknow да, это то, к чему я стремлюсь, да
3. Итак, посмотрите на мой ответ, я думаю, он делает то, что вы хотите. Если нет, скажите мне, в противном случае вы можете проголосовать и принять: D
Ответ №1:
Если я вас правильно понял, вы можете добавить это в свой onItemClick
:
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
int randomIndex = chance.nextInt(bio.get(i).size()); // generate random number between 0 and and array size
String randomString = bio.get(i).get(randomIndex); // take value from random index
Toast.makeText(getApplicationContext(),
"Sup " randomString,
Toast.LENGTH_LONG
).show();
}
Полный код основного действия (я внес только небольшие изменения, поэтому приведенное выше решение должно работать для вас):
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Random;
import static java.util.Arrays.asList;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myListView = findViewById(R.id.myListView);
final ArrayList<String> myFamily = new ArrayList<>(asList("Giovani",
"Enu",
"Xochle",
"Rquel",
"Falsto",
"Bam",
"Duncan",
"Goose",
"Edgar",
"Frank"
));
ArrayList<String> gio = new ArrayList<>(asList(" His other brother ",
" Met in high school ",
" Played on the same sports team ",
" Has two kids "
));
ArrayList<String> karina = new ArrayList<>(asList(" His youngest sister ",
" Kinda short ",
" Sweet but kinda dumb "
));
ArrayList<String> midget = new ArrayList<>(asList(" His Second youngest sister ",
" Kinda short ",
" Kinda a crazy cat lady ",
" Cannot handle her liquor "
));
ArrayList<String> ma = new ArrayList<>(asList(" His other mother ",
" Works way too hard ",
" Sweetest lady in the world "
));
ArrayList<String> pa = new ArrayList<>(asList(" His other father ",
" Not feeling well ",
" Good heart hopefully he can live in peace "
));
ArrayList<String> me = new ArrayList<>(asList(" The coolest ",
" Kinda short ",
" Sweet but kinda dumb "
));
ArrayList<String> dunks = new ArrayList<>(asList(" Brother from another mother ",
" Warrior born ",
" Allergic to most things that could hinder combat "
));
ArrayList<String> gus = new ArrayList<>(asList(" His other brother ",
" Loves cars ",
" Talks alot of shit ",
" Loves white girls ",
" Memorised the metal gear series by heart"
));
ArrayList<String> edd = new ArrayList<>(asList(" Oldest of the other brother ",
" Mostly quiet outside of social situations ",
" Cares about saving his money ",
" Laughs alot"
));
ArrayList<String> frank = new ArrayList<>(asList(" Other brother ",
" Impulsively stupid but loyal ",
" Really into recreational passions "
));
final Random chance = new Random();
final ArrayList<ArrayList<String>> bio = new ArrayList<>(asList(gio,
karina,
midget,
ma,
pa,
me,
dunks,
gus,
edd,
frank
));
ArrayAdapter<String> arrayManager = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
myFamily
);
myListView.setAdapter(arrayManager);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
int randomIndex = chance.nextInt(bio.get(i).size());
String randomString = bio.get(i).get(randomIndex);
Toast.makeText(getApplicationContext(),
"Sup " randomString,
Toast.LENGTH_LONG
).show();
}
});
}
}
Комментарии:
1. Большое спасибо, Вы не можете поверить, сколько головной боли это доставило мне!!!
2. @BernardMesh Добро пожаловать:D итак, я прихожу к выводу, что мой ответ был полезным, чтобы принять его, нажмите «поставить галочку» под голосами. Смотрите здесь