this is what I am trying to do.
I have a listview that is populated from a xml resource file saved in /values/menu.xml
it has this code in it:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="menuchoices">
<item name="pv">Present Value</item>
<item name="fv">Future Value</item>
<item name="bond">Bond Pricing</item>
</string-array>
</resources>
So far so simple. Then my Main.java file looks like this: (adapted from other listview questions here)
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.menuchoices)
));
}
public void onListItemClick(ListView partent, View v, int position, long id) {
if ("pv".equals(getResources().getStringArray(R.array.menuchoices)[position])){
setContentView(R.layout.presentvalue);
}
}
}
Basically I read that launching new activities all the time is not the best practice so i just told the if statement to change the contentview. The problem is -- Nothing happens when i click on the first item in the list. i also tried substituting "pv" with "Present Value" but it did not help either.
I think this i beacuase i took the code from posts like this here List View selection to start a new Activity) but I don't know how to change it so it works with the external xml resource file.
This should be a simple fix right?
THanks in advance
Max
P.s. all the other stuff works (the presentvalue.xml file is in the layout folder and the list is properly displayed when i run the app)
EDIT //
here is the problematic line
public void onListItemClick(ListView parent, View v, int position, long id) {
if (view.getText().toString().equals("Present Value")){
startActivity(new Intent(Main.this, PresentValue.class));
}
}
The function onListItemClick() is typically used with a ListActivity. There are a couple fixes to this:
Change the line extends Activity to extends ListActivity.
Remove your ListView definition.
Change your main.xml id from #+id/listView1 to #android:id/list
add implements OnItemClickListener in your class definition after extends Activity
Change the function onListItemClick to onItemClick
Try moving your menuchoices block:
<string-array name="menuchoices">
<item name="pv">Present Value</item>
<item name="fv">Future Value</item>
<item name="bond">Bond Pricing</item>
</string-array>
Into your string.xml file, then we can simplify your adapter (assuming you did changes #1 above):
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
R.array.menuchoices));
We can also condense how you test the menu choice:
"pv".equals(getResources().getStringArray(R.array.menuchoices)[position])
Becomes:
view.getText().toString().equals("Present Value");
(Minor point, you have a typo in the word "parent")
How's that?
Related
I have an android spinner that allows the user to select a translation. I can tap the spinner and it will reveal a list with available translations, but when I select an item in the list it will not appear in the spinner and neither does the onItemSelected method get called.
Here is the xml code for the spinner:
<Spinner
android:id="#+id/trans_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/chap_list"
android:layout_weight="1" />
Here is the relevant code for initiating the spinner. (edit) This code is ran from inside a Fragment class and not from my MainActivity class:
trans_spinner = v.findViewById(R.id.trans_list);
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_spinner_dropdown_item, translations);
trans_spinner.setAdapter(adapter);
trans_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String translation = trans_spinner.getItemAtPosition(trans_spinner.getSelectedItemPosition()).toString();
Log.d("trans", translation);
Toast.makeText(view.getContext(), translation, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("test", "1");
}
});
trans_spinner.setSelection(1);
Neither the onItemSelected() or onNothingSelected() method gets called when I select an item. I found this page describing an issue very similar to mine:
Android Spinner will not launch OnItemSelected and current selected item is not displayed in Spinner
However the user did not present a clear solution to their problem so it doesn't help me much.
I am not sure if it is relevant, but the items in the spinner are taken from an online webpage that provides JSON data to fill the spinner. This seems to work, as the options do appear in the spinner list. The issue is that upon selecting one of them, the spinner appears empty and the listener doesn't do anything.
So I found out that the issue was actually because of how I obtained the list of strings to put inside the spinner. As mentioned in the original post, I am loading the string values from a webpage in JSON format. I'm using the Retrofit2 API for this.
The problem was caused by the fact that I was downloading this data and then initializing the spinner both in the onCreateView() method of my fragment. What I did to fix it is I created a new method that initializes the spinner, and then I would call it from the onResponse() method used by the Retrofit API. This means that it doesn't initialize the spinner until after it has finished downloading/populating the list of strings.
<Spinner
android:id="#+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
f the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment (such as in the example above), you can pass this as the interface instance.
Java Code
public class MainActivity extends AppCompatActivity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
List<String> translations = new ArrayList<>();
translations.add("string1");
translations.add("string2");
translations.add("string3");
translations.add("string4");
translations.add("string5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, translations);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object getPosition = parent.getItemAtPosition(position);
String value = getPosition.toString();
Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
XML Code
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner">
</Spinner>
Add this code after init adapter
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
And to get the selected item inside onItemSelected
translations.get(position)
So, my onListItemClick is not working for some reason. I use the same code structure in another activity and that one is working perfectly. And when I try to implement the same method here, it just doesn't work at all. The Toast doesn't work. And the intent to detailactivity also doesn't work. I'm sure my naming and labeling is fine. The list items doesn't even feel like they are clickable. Can someone help me out here, please?
public class MainActivity extends ListActivity {
String objectId;
protected List<ParseObject> mInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
//**** There is a bunch of code here that takes import the list view from an adapter. I believe they are working fine. ***//
}
//**** this part below is not working. This is the section where if you click on the list item, it brings you to the detailactivity.
#Override
protected void onListItemClick(ListView l,View v, int position, long id){
super.onListItemClick(l, v, position, id);
ParseObject infoObject = mInfo.get(position);
String objectId = infoObject.getObjectId();
Toast.makeText(getApplicationContext(),objectId, Toast.LENGTH_SHORT).show();
Intent Details = new Intent(MainActivity.this, DetailsActivity.class);
Details.putExtra("objectId", objectId);
startActivity(Details);
}
İf you use a custom adapter to fill listview and involve clickable components such as Button, İmageView. onListItemClick will don't work because it won't be able to decide which component will be listened. solution is "android:focusable:"false"" keyword. thanks to this, Listener will only focus items which are populated custom adapter by you.
Like this:
<Button
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="colorCode"
/>
I have used this button to seperate each list view items. But it caused your problem. I think if you will list items, You shouldnt use clicable components in
template xml.
Happy Coding..
Vd.
Please implement the onListItemClickListener
public class MainActivity extends ListActivity implements OnItemClickListener{
//code code code
}
Then when you set the onItemCLick use
setOnItemClickListener(this);
I found an answer to solve this by adding android:focusable="false" inside of the the views in the listview/customlayout that will be imported to the activity. I got the answer from this link:
onListItemClick is not working for listview?
I want to make a popup list like above in that list there will be different distances and when i click on a distance in that distance's description will be shown from the following list. please help
atleast tell how to make popup list. For Android
Thanks
I think you're referring to a Spinner. Its very easy to use. If you're only using a specific set of values for the drop down list you can use string array resource as the source of data for the Spinner. Define in XML under the values directory an array like this. Put as many items in as you need for the Spinners drop down list.
<string-array name="distances">
<item>1 Mile</item>
<item>2 Miles</item>
</string-array>
In a layout file define a Spinner widget
<Spinner
android:id="#+id/spinnerDistances"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
And then in whatever activity you use that layout in:
Spinner spinner = (Spinner) findViewById(R.id.spinnerDistances);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.distances, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
Don't forget to define an event listener for the spinner so the program can do something when a user selects something on the Spinner.
EDIT:
To do something when an item is selected from the spinner you need to override OnItemSelectedListener.onItemSelected() and set the Spinner to use that listener with Spinner.setOnItemSelectedListener(). You can do this by making your class implement OnItemSelectedListener and implementing the required methods or something like:
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener()
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
);
Well you can create activity in android with
<activity
android:name=".youractivityname"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Dialog" />
And add list view in this activity with your desired item in the list.
The theme dialog creates your activity as a dialog and show as its a kind of popup
Please let me know if this helps you
My application consists of 2 activities.The first activity contains a TextView,if you click on it, you move to the second activity that consists of a ListView and a button Done. The ListView contains TextViews with a CheckBox. If you click on button then it finish activity and returns selected text item. If you go back to the list view the selected checkboxes restored.
Code would be appreciated.
First of all I suggest you to use CheckedTextView control instead of a CheckBox & TextView. CheckedTextView serves as the combination of checkbox and textview and is easy to handle and implement.
Secondly, you should have an ArrayList of boolean of the exact size as the ListView no. of Items. Then you can set the ArrayList items accordingly in the OnListItemClick function of ListView. At any time and anywahere in your code, you can get the reference of your selection of the ListView. Its simple and efficient.
Here is a sample OnListItemClick code:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
arrCheckBox.set(position, !arrCheckBox.get(position));
CheckedTextView ctvListItem = (CheckedTextView)v.findViewById(R.id.ctvCustomLVRowID);
ctvListItem.setChecked(arrCheckBox.get(position));
}
Here arrCheckBox is a boolean ArrayList which is keeping record of our selection and size of this array is same as no. of ListItems. I hope now you can figure it out.
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView android:id="#+id/ListView01" android:layout_height="wrap_content"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
Java code:
public class ListViewMultipleChoiceExample extends Activity {
private ListView lView;
private String lv_items[] = { "Android", "iPhone", "BlackBerry",
"AndroidPeople", "J2ME", "Listview", "ArrayAdapter", "ListItem",
"Us", "UK", "India" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
Ok, so I have this application that takes a adress strings (from values/xml) and parses it your current position) retuning a name, address and distance away. This is then picked up by an arrayadapter and put up on a listview. I cannot for the life of me get the list view to accept an onitemclick to start another activity, where I can launch a different view. I did have it where I was getting the row, name and address to show through to an alert dialog, but in my efforts to get it to launch an activity, I lost that.
So does anyone have any thoughts? I am using the following call to make my list and and arrays. This is stripped down, so assume I have all the imports and proper formatting. I know I am just missing something simple here...
public class Wf extends ListActivity {
private ArrayList<String> DistanceList;
private ArrayAdapter<String> aa;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Bind the ListView to an ArrayList of strings.
DistanceList = new ArrayList<String>();
ListView lv = (ListView)findViewById(R.id.ListView01);
aa = new ArrayAdapter<String>(getApplicationContext(),
R.layout.listbox_layout,
DistanceList);
lv.setAdapter(aa);
//Call to get distance... here
}
public void onListItemClick(ListView parent, View v,int position, long id) {
ListView lv = (ListView)findViewById(R.id.ListView01);
Toast.makeText(this, "You clicked", Toast.LENGTH_LONG).show();
}
From the ListActivity docs:
ListActivity has a default layout that
consists of a single, full-screen list
in the center of the screen. However,
if you desire, you can customize the
screen layout by setting your own view
layout with setContentView() in
onCreate(). To do this, your own view
MUST contain a ListView object with
the id "#android:id/list" (or list if
it's in code)
Your ListView does not have the correct ID. Your code is incomplete but I suspect the listener is not being registered with the ListView.