I'll try my best to make it clear.
I'm trying to create a scrollview of item (let's say it's a shop) which I (the user) add by my self VIA the interface of the app AND can then modify by clicking on it inside the scrollview.
For example, my main page contains a button and the list of items. When I click on it it opens a dialog which asks me informations of the item I want to add. When I finished configuring the item, I'm back on the main page and I can see the item I just added and i can click on it to modify it if I need to.
What I struggle with here is the fact, in a scrollview we have to add views. Even if I know how to do it via java, how can I add, for each new item, a clicklistener ? how do I set the id for each new view (items) considering the fact that I only can set int ids ? etc.
Does someone knows any way to do what I try to ? I'll make a very simple example of code and interfaces screenshot here in order to be very clear.
My XML MainPage : "activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/popUpAddItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Your Item"
tools:ignore="MissingConstraints">
</Button>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewItems">
<!-- this LinearLayout is an exemple of the shape/structure of an item -->
<LinearLayout
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/protoItem">
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Item1 "
android:id="#+id/protoName">
</TextView>
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Qt1 "
android:id="#+id/protoQuantity">
</TextView>
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Price1 "
android:id="#+id/protoPrice">
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
XML of the custom pop-up: "dialog_popup.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/window"
tools:ignore="MissingConstraints">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemName"
android:hint="Enter the name of the item">
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemQuantity"
android:hint="Enter the quantity of the item">
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemPrice"
android:hint="Enter the price the item">
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valider"
android:id="#+id/validationButton">
</Button>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Class to create a custom pop-up: "CreateCustomPopUp.java
package com.example.myapplication;
import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class CreateCustomPopUp extends Dialog {
private LinearLayout page;
private EditText name, quantity, price;
private Button validation;
private String varName="";
private int varQt= 0;
private float varPrice =0;
public CreateCustomPopUp(Activity activity)
{
super(activity, androidx.appcompat.R.style.Theme_AppCompat_Dialog);
setContentView(R.layout.dialog_popup);
this.page = findViewById(R.id.window);
this.name = findViewById(R.id.itemName);
this.price = findViewById(R.id.itemPrice);
this.quantity = findViewById(R.id.itemQuantity);
this.validation = findViewById(R.id.validationButton);
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
varName=name.getText().toString();
varQt=Integer.valueOf(quantity.getText().toString());
varPrice=Float.valueOf(price.getText().toString());
dismiss();
}
});
}
public void build()
{
show();
}
public int getQt(){
return varQt;
}
public String getName(){
return varName;
}
public float getPrice(){
return varPrice;
}
}
Main activity Java : "MainActivity.java"
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
public MainActivity activity;
public String name ="";
public int qt =0;
public float price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.activity=this;
Button addItem = (Button) findViewById(R.id.popUpAddItem);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateCustomPopUp popUp = new CreateCustomPopUp(activity);
popUp.build();
popUp.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
name = popUp.getName();
qt = popUp.getQt();
price = popUp.getPrice();
//Put/call here a function/class or whatever works that add this created item in the scrollview
}
});
}
});
LinearLayout prototypeItem = (LinearLayout) findViewById(R.id.protoItem);
prototypeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Another popup that I'm borred to create, but I think you see the idea...
}
});
// and here is my issue : I cant reproduce this "set on click listener" for each item... because they dont already exist and I dont know how many I'll have !
}
}
Hope it's clear and you can help me ^^
bye
Use a <RecyclerView> instead. RecyclerView is the best choice when you have multiple items of same type and you have to dynamically modify them. Follow these links to learn about recycler view and click listener in recycler view RecyclerView example. Recycler View Click Listener. I will briefly discuss how to do this.
Create a item layout file. This is basically how each item of your recycler view looks. In your case this will be LinearLayout of protoitem declared in separate xml file.
Create a data model file that defines that represents your single entity. eg. Create a class Item with fields name, quantity, price and appropriate methods.
Add only recyler view in your activity_main.xml
Create an adapter that loads your data into recycler view and link your adapter to recycler view.
Create a list of your custom Item class List<Item> myList = new ArrayList<>();
Now whenever you add new Item via dialog just add your item in myList and update your adapter by adapter.notifyDataSetChanged(); Adapter will automatically add that item in your recycler view.
For click listener you need to create an interface in your adapter and implement that click listener in you main activity.
Related
This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
findViewById returns null
(4 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I've created a Location class and when I click on Cinemas in MainActivity, I want to open another activity that contains the list of Location objects. For this goal I have created a custom location_list_item layout file and a custom ArrayAdapter. For some reason, when I click on Cinemas, my app crashes. Why?
MainActivity.java
package com.example.android.tourguide;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View cinemasView = findViewById(R.id.cinemas_layout);
cinemasView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
CinemasActivity.class);
startActivity(intent);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:background="#fff8e1"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_activity_title"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"/>
<LinearLayout
android:id="#+id/cinemas_layout"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#4a148c">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/category_cinemas"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/category_cinemas"
android:textSize="25sp"
android:textColor="#android:color/white"/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
<LinearLayout
android:id="#+id/restaurants_layout"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#4a148c">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/category_restaurants"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/category_restaurants"
android:textSize="25sp"
android:textColor="#android:color/white"/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
<LinearLayout
android:id="#+id/gyms_layout"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#4a148c">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/category_gyms"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/category_gyms"
android:textSize="25sp"
android:textColor="#android:color/white"/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
<LinearLayout
android:id="#+id/parks_layout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#4a148c">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/category_parks"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/category_parks"
android:textSize="25sp"
android:textColor="#android:color/white"/>
</LinearLayout>
</LinearLayout>
location_category_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/location_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/location_hours_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="Hours"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/location_working_days"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
tools:text="Every Day" />
<TextView
android:id="#+id/location_working_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
tools:text="09:00 – 00:00" />
</LinearLayout>
<TextView
android:id="#+id/location_address_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="Address"
android:textStyle="bold"/>
<TextView
android:id="#+id/location_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
tools:text="09:00 – 00:00" />
<TextView
android:id="#+id/location_phone_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="Phone"
android:textStyle="bold"/>
<TextView
android:id="#+id/location_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
tools:text="+7 (555) 555-55-55" />
</LinearLayout>
Location.java
package com.example.android.tourguide;
import androidx.annotation.NonNull;
public class Location {
private int mImageResourceId;
private String mAddress;
private String mPhone;
private String mWorkingDays;
private String mWorkingHours;
public Location(int imageResourceId, String address, String phone,
String workingDays, String workingHours) {
mImageResourceId = imageResourceId;
mAddress = address;
mPhone = phone;
mWorkingDays = workingDays;
mWorkingHours = workingHours;
}
public int getImageResourceId() {
return mImageResourceId;
}
public String getAddress() {
return mAddress;
}
public String getPhone() {
return mPhone;
}
public String getWorkingDays() {
return mWorkingDays;
}
public String getWorkingHours() {
return mWorkingHours;
}
#NonNull
#Override
public String toString() {
return mImageResourceId + mAddress + mWorkingDays + mWorkingDays + mPhone;
}
}
LocationAdapter.java
package com.example.android.tourguide;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class LocationAdapter extends ArrayAdapter<Location> {
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the list is the data we want
* to populate into the lists.
*
* #param context The current context. Used to inflate the layout file.
* #param locations A List of Location objects to display in a list
*/
public LocationAdapter(Activity context, ArrayList<Location> locations) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for one ImageView and 4 TextViews, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, locations);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The position in the list of data that should be displayed in the
* list item view.
* #param convertView The recycled view to populate.
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null)
{
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.location_category_list_item, parent,
false);
}
// Get the {#link Location} object located at this position in the list
Location currentLocation = getItem(position);
// Find the ImageView in the location_category_list_item.xml layout
// with the ID location_image
ImageView image = listItemView.findViewById(R.id.location_image);
// Get the image resource ID from the current Location object and
// set the image to imageView
image.setImageResource(currentLocation.getImageResourceId());
// Find the TextView in the location_category_list_item.xml layout
// with the ID location_working_days
TextView workingDaysTextView = listItemView.findViewById(R.id.location_working_days);
// Get the working days from the current Location object and
// set this text on the workingDaysTextView
workingDaysTextView.setText(currentLocation.getWorkingDays());
// Find the TextView in the location_category_list_item.xml layout
// with the ID location_working_hours
TextView workingHoursTextView = listItemView.findViewById(R.id.location_working_hours);
// Get the working hours from the current Location object and
// set this text on the workingHoursTextView
workingHoursTextView.setText(currentLocation.getWorkingHours());
// Find the TextView in the location_category_list_item.xml layout
// with the ID location_address
TextView addressTextView = listItemView.findViewById(R.id.location_address);
// Get the address from the current Location object and
// set this text on the addressTextView
addressTextView.setText(currentLocation.getAddress());
// Find the TextView in the location_category_list_item.xml layout
// with the ID location_phone
TextView phoneTextView = listItemView.findViewById(R.id.location_phone);
// Get the address from the current Location object and
// set this text on the phoneTextView
phoneTextView.setText(currentLocation.getPhone());
// Return the whole list item layout
// so that it can be shown in the ListView
return listItemView;
}
}
CinemasActivity.java
package com.example.android.tourguide;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class CinemasActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_category_list_item);
//Create a list of cinemas
final ArrayList<Location> locations = new ArrayList<>();
locations.add(new Location(R.drawable.cinemas_byl,
"Zhukova mikrorayon, 38",
"+7 (929) 002-20-09",
"Every Day",
"09:00 – 00:00"));
locations.add(new Location(R.drawable.cinemas_charly,
"Ol'minskogo mikrorayon, 17",
"+7 (472) 523-34-56",
"Every Day",
"09:30 – 02:00"));
locations.add(new Location(R.drawable.cinemas_cinema_5,
"Molodezhnyy Proyezd, 10",
"+7 (472) 523-37-27",
"Every Day",
"09:00 – 00:00"));
// Create an {#link LocationAdapter}, whose data source is a list of
// {#link Locations}. The adapter knows how to create list item views
// for each item in the list.
LocationAdapter locationAdapter = new LocationAdapter(this, locations);
// Get a reference to the ListView, and attach the adapter to the listView.
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(locationAdapter);
}
}
Probably you set wrong layout in your CinemasActivity.
setContentView(R.layout.location_category_list_item);
R.layout.location_category_list_item is item view for your ListView.
There is no ListView in location_category_list_item which causes the crash
listview.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:id="#+id/lstText">
</ListView>
</LinearLayout>
ListView Code
package saint.animaltracking;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.List;
import saint.animaltracking.helper.AnimalAdapter;
import saint.animaltracking.helper.DatabaseHelper;
/**
* Created by Kodie on 3/28/2016.
*/
public class selectAnimal extends AppCompatActivity
{
private ListView lv;
private List<animal> animal;
private DatabaseHelper db;
AnimalAdapter adapter;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
db = new DatabaseHelper(this.getApplicationContext());
setContentView(R.layout.main);
animal = db.getAllAnimal();
lv = (ListView) findViewById(R.id.lstText);
adapter = new AnimalAdapter(this, R.layout.list_item, animal);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
animal anim = (animal) lv.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), specific.class);
intent.putExtra("animal", anim);
startActivity(intent);
}
});
}
}
specific.class xml (Generic as I am trying to debug the issue)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/btnButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"/>
<Button
android:id="#+id/btnButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:layout_toRightOf="#+id/btnButton1"/>
<Button
android:id="#+id/btnButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:layout_below="#+id/btnButton1"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnButton3"
android:layout_marginTop="94dp"
android:text="User :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:layout_toRightOf="#+id/btnButton3" />
<Button
android:id="#+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/editText1"
android:text="Submit" />
</RelativeLayout>
Specific.java code
package saint.animaltracking;
import android.content.Intent;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* Created by Kodie on 5/2/2016.
*/
public class specific extends AppCompatActivity {
String id;
private SQLiteOpenHelper AT;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.specific);
Intent intent = getIntent();
}
}
The issue I am running into is that when I click the specific listview item to go to the specific animal, all it shows is a blank page. I'm not really sure why though, but I have a strong feeling it has something to do with the way I am writing the OnItemClickListener and OnItemClick or how it is passing the intent to the specific.java class? I've done just about everything I can think of (I've been working in android for about three weeks) to resolve this, outside of trying to rewrite the OnItemClickListener section. Any tips in the right direction are greatly appreciated. Thanks in advance.
UPDATE:
I get the following messages repeatedly when clicking the listitem
W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent...
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40d53a0
Try to define some textview with random text in spesific class.. or something like Toast, to prove that spesific class is running or not.
I Have a spinner displaying a list from an array, what I want to do is have the selected option display a more detailed selection in a window below the array.
The reason I am after this is I want to build a character creation tool and I want people to be able to pick from a list of option and then depending on the option they select bring up a description of what that selection means.
So far I have my Array in strings.xml which is:
<string-array name="humanBackgroundData">
<item>Cultist</item>
<item>Freed Slave</item>
<item>Gangster</item>
<item>Techno-Reaper</item>
<item>Tribal</item>
<item>Wanderer</item>
<item>Dwelled in the Dwelling</item>
<item>Feral Child</item>
<item>Welsh/Scottish Descendant</item>
</string-array>
And my Spinner which is in the activity.xml:
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinB"
android:entries="#array/humanBackgroundData"
android:paddingBottom="20dp"
>
I have been searching for a way to link the selected option to another string which could then show additional data for that selection. I want to do this because having a ton of data in the spinner will look terrible. I have seen methods of numbering the spinner so that the first selection would be 1 and the second 2 so I believe I should be able to use that as a reference to invoke a string, but I have only been working with android studio for around two weeks and I cannot find any other posts about doing this. any suggestions?
Thanks for your time :)
Update
I have now partialy found a solution, I can now get the TextView to reference the string if I contain it within the activity, however I want to pull it from strings.xml so it keeps things a bit tidier and stops me repeating myself so much. I have linked my code below. If I replace the "textnone" with "text1" it works so I think it is just a problem with the way I have linked the string array.
<string-array name="humanBackgroundData">
<item>Cultist</item>
<item>Freed Slave</item>
<item>Gangster</item>
<item>Techno-Reaper</item>
<item>Tribal</item>
<item>Wanderer</item>
<item>Dwelled in the Dwelling</item>
<item>Feral Child</item>
<item>Welsh/Scottish Descendant</item>
</string-array>
package com.studios.grimvoodoo.spicedcharacterbuilder;
import android.content.res.Resources;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class HumanActivity extends Activity {
private static Button proceed;
Resources res = getResources();
String[] text1 = res.getStringArray(R.array.ghulBackgroundData);
String[] textnone = {"human", "ghul", "postgen",
"gnome", "pixie", "giant", "vampire"};
String[] text2 = {"standard", "undead", "super mutant", "wee man", "flying wee man", "big and hungry", "dead and loving it"};
Spinner spinner1;
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_human);
textView1 = (TextView) findViewById(R.id.text1);
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(HumanActivity.this,
android.R.layout.simple_spinner_item, text1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(text2[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.studios.grimvoodoo.spicedcharacterbuilder.HumanActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<Spinner
android:id="#+id/spinner0"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text0"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<string-array name="humanBackgroundData">
<item>Cultist</item>
<item>Freed Slave</item>
<item>Gangster</item>
<item>Techno-Reaper</item>
<item>Tribal</item>
<item>Wanderer</item>
<item>Dwelled in the Dwelling</item>
<item>Feral Child</item>
<item>Welsh/Scottish Descendant</item>
</string-array>
If I understood you right, you should put additional TextView below Spinner in layout. Then create separate string array with additional infos (info array), with same size as your existing string array.
Then in spinner's onItemSelected(AdapterView parent, View view, int pos, long id) method, get position of selected spinner element (pos) and update TextView with corresponding element from your infos array (element with index pos).
I am making an app that shows a list of campfire songs, and currently all I can see on my app is a list of all the songs and when clicked on, they open up another activity. The next activity that is opened looks how I want it to, but the list of songs on the first activity (menu) only shows a list with no formatting around it or any images or buttons that I have specified in the XML. - I haven't linked these up in the code as they stop the list from appearing at all.
Here is my Java file for Menu.java:
package com.lmarshall1995.scoutsongs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity{
String classes[] = {"......"};
String items[] = {"......"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, items));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String song_activity = classes[position];
try{
Class<?> ourClass = Class.forName("com.lmarshall1995.scoutsongs." + song_activity);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
And here is my XML file for menu.xml that I would like the list to be put in (#+id/list):
<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" xmlns:app="http://schemas.android.com/apk/lib/com.google.ads">
<TextView
android:id="#+id/SelectSong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#android:id/list"
android:layout_alignTop="#+id/ic_launcher"
android:text="#string/SelectSong"
android:textSize="20sp" />
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="320dp"
android:layout_below="#+id/ic_launcher"
tools:listitem="#android:layout/simple_list_item_1" >
</ListView>
<ImageView
android:id="#+id/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:contentDescription="#string/ic_launcher"
android:src="#drawable/ic_launcher" />
<ImageButton
android:id="#+id/settings_button"
android:src="#drawable/settings_button_selected"
android:contentDescription="#string/action_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<ImageButton
android:id="#+id/exit_button"
android:src="#drawable/exit_button_selected"
android:contentDescription="#string/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
I was wondering if someone could help me turn what I think is the android.R.layout.simple_list_item_1 into my list (#+id/list) from my menu.xml file. Any suggestions?
Thanks,
From
Laurence =]
Call setContentView(R.layout.menu) in onCreate before calling setListAdapter.
You have to use a custom adapter to do that, create a class tha extens BaseAdapter or ArrayAdapter and use that instead of the simple android adapter.
See here a tutorial.
I used the instructions given Here: http://developer.android.com/guide/topics/ui/dialogs.html#AddingAList to create a List in a dialog.
The problem is I don't seem to find out a way to wrap long text inside the options. [Please see the image below]
Please tell me how to do the text wrapping. :(
I am using the following code:
items= getArrayFromJson(source+"getdetails.php?brand="+bName+"&car="+cName);
builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Model");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("No Options Available")){
dismissDialog(2);
}
else{
model.setText(items[item]);
mName= items[item].toString();
location.setEnabled(true);
dismissDialog(2);
}
}
});
alert = builder.create();
return alert;
Any help/direction is highly appreciated :)
At first I would create a list layout... something like:
list_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp" />
</LinearLayout>
Then a simple TextView like:
single_item_layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/singleItem"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#FFFFFF"
android:padding="10dp"
android:text="blue thingy"
android:background="#336699" />
</LinearLayout>
and a simple main layout:
main
<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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:onClick="popUp"
android:text="pop dialog list" />
</RelativeLayout>
lastly a simple main Activity:
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void popUp(View v){
// Dummy list:
ArrayList<String> dummies = new ArrayList<String>();
dummies.add("dumm1");
dummies.add("dumm2");
dummies.add("dumm3");
dummies.add("dumm4");
dummies.add("dumm5");
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.list_layout);
dialog.setTitle("List Title");
ListView listView = (ListView) dialog.findViewById(R.id.list);
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.single_item_layout , R.id.singleItem, dummies);
listView.setAdapter(ad);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//do something on click
dialog.dismiss();
}
});
dialog.show();
}
}
and that's all.
I tried to make that as simple as possible, you can google for ideas to make your list a bit attractive, like here.