Open Multiple Listview Item Click to One Class - android

Hope you guys can help.
I have a activity which handles all the 10 image button clicks and list view intents. What i am looking to do is have 1 layout for all the list view button clicks. And in this layout call different data to it. When i started this project i had many activitys until a great stack overflow user pointed out that i can make it simpler which i did and made it a lot clear.
package com.example.testtest;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Listviewact extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.listview_layout);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/AlexBrush-Regular-OTF.otf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
}
public void onResume() {
super.onResume();
int buttonId = getIntent().getIntExtra("buttonId", 0);
int buttonIdx = getButtonIdx(buttonId);
// find and set image according to buttonId
int imageId = IMAGE_IDS[buttonIdx]; // image to show for given button
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(imageId);
// find and set listview imtes according to buttonId
String[] items = LISTVIEW_DATA[buttonIdx]; // listview items to show for given button
ListView listView = (ListView)findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
}
private void setListAdapter(ArrayAdapter adapter) {
// TODO Auto-generated method stub
}
// a little helper to map ids to array indices
// to be able to fetch the correct image and listview data later
private final static int[] BUTTON_IDS = new int[] {
R.id.imageButton1,
R.id.imageButton2,
R.id.imageButton3,
R.id.imageButton4,
R.id.imageButton5,
R.id.imageButton6
};
// 6 images
private final static int[] IMAGE_IDS = new int[] {
R.drawable.bmw,
R.drawable.ford,
R.drawable.honda,
R.drawable.toy,
R.drawable.vok2,
R.drawable.ic_launcher
};
// 6 different sets of strings for the listviews
private final static String[][] LISTVIEW_DATA = new String[][] {
{"First A", "First B", "First C", "First D","First E","First F"},
{"Second A", "Second B", "Second C"},
{"Third A", "Third B", "Third C"},
{"Forth A", "Forth B", "Forth C"},
{"Fifth A", "Fifth B", "Fifth C"},
{"Sixth A", "Sixth B", "Sixth C"},
};
// map button id to array index
static private int getButtonIdx(int id) {
for(int i = 0; i<BUTTON_IDS.length; i++) {
if (BUTTON_IDS[i] == id) return i;
}
return 0; // should not happen
}
}
It would be great if someone can show me how to make a class which i can call all the item clicks from all list views too from my code here.
package com.example.testtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_of_button);
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
case R.id.imageButton1:
case R.id.imageButton2:
case R.id.imageButton3:
case R.id.imageButton4:
case R.id.imageButton5:
case R.id.imageButton6:
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
CHEERS.
http://img40.imageshack.us/img40/705/f6h9.png

If I understand what you want, you could create a class with something like a static Arraylist to be appended each time an item is clicked. So create a class something like
public class Data class
{
static ArrayList<String> dataArray = new ArrayList<String>();;
public Data()
{
// empty constructor but could be used if needed
}
Then you can add different getters/setters or whatever you need here. When you click on an item you just call something like
Data.dataArray.add("stuff");
then retrieve items in here in your next Activity.
If that is too complicated or more than you need then you can just pass an ArrayList or whatever object you need through the Intent
Intents
Also, just a preference but since all of your Buttons do the same thing, you can do away with initializing them and setting listeners on all of them. In xml just add
`android:onClick="someFunctionName"`
to each Button then use that function name
public void someFunctionName(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
There is also no need for the case statements since they all do the same thing and you don't need implements OnClickListener in the Activity declaration

You're using the ListView but not using any of it's callbacks? Here, this is my code that I use for my ListView. I'm putting activities in my array, but you could put anything. Modifying the R.layout.mfd_view allows you to put whatever you want for each list item. A Button if that's what you need. Hope this helps. I'm still learning myself.
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MyListFragment extends ListFragment {
String fragmentBackStack;
MyMapHandler handler;
OnViewSelectedListener mListener;
/**
* An array of POJOs used to hold the info about the fragments we'll be
* swapping between This should be inserted into an array adapter of some
* sort before being passed onto ListAdapter
*/
private static final ViewDetails[] ACTIVITY_DETAILS = {
new ViewDetails(R.string.action_largeTach,
R.string.largeTach_description, LargeTachActivity.class),
new ViewDetails(R.string.action_map, R.string.map_description,
MyMapHandler.class),
new ViewDetails(R.string.action_navigation,
R.string.navigation_description, NavigationActivity.class),
new ViewDetails(R.string.action_raceMode,
R.string.raceMode_description, RaceModeActivity.class),
new ViewDetails(R.string.action_settings,
R.string.settings_description, SettingsFragment.class),
new ViewDetails(R.string.action_extraInfo,
R.string.extraInfo_description, ExtraInfoActivity.class) };
/**
* #author PyleC1
*
* A POJO that holds a class object and it's resource info
*/
public static class ViewDetails {
private final Class<? extends Activity> viewActivity;
private int titleId;
private int descriptionId;
/**
* #param titleId
* The resource ID of the string for the title
* #param descriptionId
* The resource ID of the string for the description
* #param activityClass
* The fragment's class associated with this list position
*/
ViewDetails(int titleId, int descriptionId,
Class<? extends Activity> viewActivity) {
super();
this.titleId = titleId;
this.descriptionId = descriptionId;
this.viewActivity = viewActivity;
}
public Class<? extends Activity> getViewActivity() {
return viewActivity;
}
}
/**
* #author PyleC1
*
* Extends the ArrayAdapter class to support our custom array that
* we'll insert into the ListAdapter so the user can pick between
* MFD screens at boot time.
*/
private static class CustomArrayAdapter extends ArrayAdapter<ViewDetails> {
public CustomArrayAdapter(Context context, ViewDetails[] activities) {
super(context, R.layout.mfd_view, R.id.mfdTitle, activities);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MFDView mfdView;
if (convertView instanceof MFDView) {
mfdView = (MFDView) convertView;
} else {
mfdView = new MFDView(getContext());
}
ViewDetails details = getItem(position);
mfdView.setTitleId(details.titleId);
mfdView.setDescriptionId(details.descriptionId);
return mfdView;
}
}
public void onAttach(Activity activity) {
super.onAttach(activity);
ListAdapter listAdapter = new CustomArrayAdapter(getActivity(),
ACTIVITY_DETAILS);
setListAdapter(listAdapter);
try {
mListener = (OnViewSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnViewSelectedListener!");
}
}
#Override
public void onResume() {
super.onResume();
}
public interface OnViewSelectedListener {
public void onViewSelected(Class<? extends Activity> activityClass);
}
public void onListItemClick(ListView l, View v, int position, long id) {
ViewDetails details = (ViewDetails) getListAdapter().getItem(position);
mListener.onViewSelected(details.viewActivity);
}
}
Note that whatever activity calls this fragment must implement the OnViewSelectedListener interface. If you added this to your main activity as a subclass, this wouldn't be required. The public void onListItemClick(arg0, arg1, arg2, arg3) callback is fine. You just swap fragments or call activities from inside there.

Related

How to simulate button press in Android

Here's my MainActivity.java, in the onClick() method I want to swap the values between the spinners and also automatically do an internal button press when buttonSwap is pressed. I can swap the Spinners and texts values but can not do inner call to buttonConvert for auto conversion upon buttonSwap press . Please Help:
MainActivity.java file code :
package com.gazzali.spinitmeow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener{
Spinner spinnerMainChoice;
Spinner spinnerInputChoice;
Spinner spinnerOutputChoice;
EditText InputValueEditText;
Double inputValue;
TextView outputValueTextView;
Button buttonConvert;
Button buttonReset;
Button buttonSwap;
String selectedMainChoice;
String inputValueString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* ------------ Main code Starts Here ----------------*/
/* Main conversion Type choice with Spinner (Drop Down menu)*/
spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
// [IMPORTANT] Set Spinner Click Listener
spinnerMainChoice.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
R.array.MainChoices_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerMainChoice.setAdapter(adapterMainChoice);
/* Input Conversion type choice with Spinner */
spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
/* Output Conversion type choice with Spinner */
spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
/* for input and output fields */
InputValueEditText = findViewById(R.id.editTextIDInputValue);
/* ---- Setting Button Properties -----*/
buttonConvert = findViewById(R.id.buttonIDConvert);
buttonConvert.setOnClickListener(this);
buttonReset = findViewById(R.id.buttonIDReset);
buttonReset.setOnClickListener(this);
buttonSwap = findViewById(R.id.buttonIDSwap);
buttonSwap.setOnClickListener(this);
/* --- Setting Output TextView field ----*/
outputValueTextView = findViewById(R.id.textViewIDoutputValue);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. retrieve the selected item
selectedMainChoice = parent.getSelectedItem().toString();
Log.i("Selected", selectedMainChoice);
/* Toast.makeText(MainActivity.this, String.valueOf(inputValue), Toast.Weight_SHORT).show();*/
/* Implement object of spinnerSelects class*/
spinnerSelects spinnerSelectsInMain = new spinnerSelects(this, spinnerInputChoice, spinnerOutputChoice);
/* the main EVIL '(context) this' in the 2nd paraKilogram, 5 hours wasted, but I learnt many more */
spinnerSelectsInMain.setInputOutputSpinners(selectedMainChoice);
/* calling test for converter class */
/*testOnConverter();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void testOnConverter(){
converter converterInMain = new converter(selectedMainChoice);
}
#Override
public void onClick(View view)
{
if (view == buttonConvert) {
inputValueString = InputValueEditText.getText().toString();
inputValue = Double.parseDouble(inputValueString);
/*Toast.makeText(this, String.valueOf(inputValue), Toast.Weight_SHORT).show();*/
converter converterInMain = new converter(selectedMainChoice);
double convertedValue = converterInMain.convert(inputValue);
outputValueTextView.setText(String.valueOf(convertedValue));
}
else if(view == buttonReset)
{
InputValueEditText.getText().clear();
outputValueTextView.setText("0.00");
}
else if(view == buttonSwap)
{
/* Swap between spinners choice */
spinnerSelects spinnerSelectsInMainToSwap= new spinnerSelects();
spinnerSelectsInMainToSwap.swapEverything();
/* Here I want to simulate as the buttonConvert has been pressed */
/* performClick() or callOnClick() doesn't simulate the convert button press programmatically */
}
}
}
Create three functions
void buttonConvert(){
...code for buttonconvert();
}
void buttonSwap(){
...code for buttonswap();
}
void buttonReset(){
...code for buttonreset();
}
then in the condition blocks
if(buttonConvert){
buttonConvert();
}
else if(buttonSwap){
buttonSwap();
buttonConvert();
}
else if(buttonReset){
buttonReset();
}
You can simulate click by doing buttonConvert.performClick();.
Or you can call manually onClick method and pass buttonCovert view like onClick(buttonConvert);

Adding a Listview to Case Statement

I have been playing around with this code for days now if someone can help. I have 10 imagebutton in one layout i have all the button clicks in a case statement which takes care of them.What i need is to have a listview inside all the buttons when clicked.Now i have some good code from Ridcully
Listview On Multiple Button Clicks. I just can seem to get it to work
FirstActivity
package com.example.testtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_of_button);
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
case R.id.imageButton1:
case R.id.imageButton2:
case R.id.imageButton3:
case R.id.imageButton4:
case R.id.imageButton5:
case R.id.imageButton6:
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Listviewact
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class Listviewact extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.listview_layout);
}
public void onResume() {
super.onResume();
int buttonId = getIntent().getIntExtra("buttonId", 0);
int buttonIdx = getButtonIdx(buttonId);
// find and set image according to buttonId
int imageId = IMAGE_IDS[buttonIdx]; // image to show for given button
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(imageId);
// find and set listview imtes according to buttonId
String[] items = LISTVIEW_DATA[buttonIdx]; // listview items to show for given button
ListView listView = (ListView)findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
private void setListAdapter(ArrayAdapter adapter) {
// TODO Auto-generated method stub
}
// a little helper to map ids to array indices
// to be able to fetch the correct image and listview data later
private final static int[] BUTTON_IDS = new int[] {
R.id.imageButton1,
R.id.imageButton2,
R.id.imageButton3,
R.id.imageButton4,
R.id.imageButton5,
R.id.imageButton6
};
// 6 images
private final static int[] IMAGE_IDS = new int[] {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
// 6 different sets of strings for the listviews
private final static String[][] LISTVIEW_DATA = new String[][] {
{"First A", "First B", "First C"},
{"Second A", "Second B", "Second C"},
{"Third A", "Third B", "Third C"},
{"Forth A", "Forth B", "Forth C"},
{"Fifth A", "Fifth B", "Fifth C"},
{"Sixth A", "Sixth B", "Sixth C"},
};
// map button id to array index
static private int getButtonIdx(int id) {
for(int i = 0; i<BUTTON_IDS.length; i++) {
if (BUTTON_IDS[i] == id) return i;
}
return 0; // should not happen
}
}
when i start it the button click works but no listview ??
You have to use listView.setListAdapter(adapter); as shown in the example code of my answer to your previous question. You're calling your own setListAdapter method which does nothing, so the listView has no adapter to get the data from.

Having an issue with switch statement involving Android Spinners

I'm trying to use 2 spinners on my view and at the moment implementing the "OnItemSelected" method . I have a switch statement set up to tell the spinners apart, but it doesn't seem to be working for some reason.
Here is my code:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* This is the activity for feature 1 in the dashboard application.
* It displays some text and provides a way to get back to the home activity.
*
*/
public class F1Activity extends DashboardActivity implements OnItemSelectedListener
{
/**
* onCreate
*
* Called when the activity is first created.
* This is where you should do all of your normal static set up: create views, bind data to lists, etc.
* This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
*
* Always followed by onStart().
*
* #param savedInstanceState Bundle
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f1);
setTitleFromActivityLabel (R.id.title_text);
//declaring variables
Button submitButton = (Button) findViewById(R.id.button1);
Button cancelButton = (Button) findViewById(R.id.button2);
//getting arrays from strings file
String[] regions = getResources().getStringArray(R.array.regions_array);
String[] grids = getResources().getStringArray(R.array.grids_array);
Spinner gridSpinner = (Spinner) findViewById(R.id.gridSpinner);
Spinner regionSpinner = (Spinner) findViewById(R.id.regionSpinner);
//creating adapters for both spinners
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, grids);
ArrayAdapter<String> regionAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, regions);
// drop down layout style with radio button type.
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapters to spinners
gridSpinner.setAdapter(dataAdapter);
regionSpinner.setAdapter(regionAdapter);
gridSpinner.setOnItemSelectedListener(this);
regionSpinner.setOnItemSelectedListener(this);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
EditText nameText = (EditText) findViewById(R.id.nameTextBox);
EditText passText = (EditText) findViewById(R.id.passwordTextBox);
if(nameText.getText().toString().length() > 0 &&
passText.getText().toString().length() > 0) //TAKE CARE OF LISRVIEW/DROPDOWN
{
Toast.makeText(getApplicationContext(),
"Loading...", Toast.LENGTH_LONG).show();
// make an intent to start the virtual world activity..................like in addGridActivity/screen switch!
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Sorry, you have to complete all the fields",
Toast.LENGTH_SHORT).show();
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
// cancelled and went back to home screen
finish();
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long arg3) {
// to handle the selection of the gridSpinner or the regionSpinner
int id = parent.getId();
switch(id)
{
case R.id.gridSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the grid spinner", Toast.LENGTH_LONG);
break;
case R.id.regionSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the region spinner", Toast.LENGTH_LONG);
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} // end class
<code>
Your switch is working fine. The reason it seems to be not working is because your code to display the Toast is missing the show() calls.
Instead of:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG);
do this:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG).show();
I make the same mistake all the time myself :)
Replace int id = parent.getId(); to int id = view.getId();
You need to switch based on the id of the view not the view adapter. Try changing int id = parent.getId(); to int id = view.getId();.

identify what I have chosen from a wheel android

I am using the code for the wheel chooser from here. So lets say that i want to implement something like the citiesactivities.java. Code is below. What I want now is:
when the user chooses with the slider what he want, press a button Go and take him to a new activity.
So I must insert somewhere a buttonOnClickListener but I do not know where? I mean where in the code, the item selected by the user is specified? I mean if select Canada and Vancouver, press go and take him to CanadaVancouverActivity, if Toronto to CanadaTorontoActivity and so on.
Code is here:
package kankan.wheel.demo;
import kankan.wheel.R;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class CitiesActivity extends Activity {
// Scrolling flag
private boolean scrolling = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cities_layout);
final WheelView country = (WheelView) findViewById(R.id.country);
country.setVisibleItems(3);
country.setViewAdapter(new CountryAdapter(this));
final String cities[][] = new String[][] {
new String[] {"New York", "Washington", "Chicago", "Atlanta", "Orlando"},
new String[] {"Ottawa", "Vancouver", "Toronto", "Windsor", "Montreal"},
new String[] {"Kiev", "Dnipro", "Lviv", "Kharkiv"},
new String[] {"Paris", "Bordeaux"},
};
final WheelView city = (WheelView) findViewById(R.id.city);
city.setVisibleItems(5);
country.addChangingListener(new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!scrolling) {
updateCities(city, cities, newValue);
}
}
});
country.addScrollingListener( new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
scrolling = true;
}
public void onScrollingFinished(WheelView wheel) {
scrolling = false;
updateCities(city, cities, country.getCurrentItem());
}
});
country.setCurrentItem(1);
}
/**
* Updates the city wheel
*/
private void updateCities(WheelView city, String cities[][], int index) {
ArrayWheelAdapter<String> adapter =
new ArrayWheelAdapter<String>(this, cities[index]);
adapter.setTextSize(18);
city.setViewAdapter(adapter);
city.setCurrentItem(cities[index].length / 2);
}
/**
* Adapter for countries
*/
private class CountryAdapter extends AbstractWheelTextAdapter {
// Countries names
private String countries[] =
new String[] {"USA", "Canada", "Ukraine", "France"};
// Countries flags
private int flags[] =
new int[] {R.drawable.usa, R.drawable.canada, R.drawable.ukraine, R.drawable.france};
/**
* Constructor
*/
protected CountryAdapter(Context context) {
super(context, R.layout.country_layout, NO_RESOURCE);
setItemTextResource(R.id.country_name);
}
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
ImageView img = (ImageView) view.findViewById(R.id.flag);
img.setImageResource(flags[index]);
return view;
}
#Override
public int getItemsCount() {
return countries.length;
}
#Override
protected CharSequence getItemText(int index) {
return countries[index];
}
}
}
Finally I found the answer. There is a function in the package named getCurrentItem().

Best way to start a new activity from a clicked listview

I have an array that successfully shows as a listview as the main activity. I've been using many tutorials in the past few days to try to find out the best way to start different activities from items clicked on this listview. I've seen everything from switch statements to calling a class by a variable, but nothing seems to work. I would possibly use an if statement but my list is over 120 entries. Any suggestions?
Why don't you put the class as a parameter of the item ?
package com.ybi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class YbiListActivity extends ListActivity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
ClickableItem[] values = new ClickableItem[1];
// here you can add your label and your activity
values[0] = new ClickableItem("Hello", YbiListActivity.class);
ArrayAdapter<ClickableItem> adapter = new ArrayAdapter<ClickableItem>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
ClickableItem item = (ClickableItem) getListAdapter().getItem(position);
Intent intent = new Intent(YbiListActivity.this, (Class<?>) item.itemClass);
startActivity(intent);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
private class ClickableItem
{
public String itemLabel;
public Object itemClass;
public ClickableItem(String ilabel, Object iclass)
{
itemLabel = ilabel;
itemClass = iclass;
}
#Override
public String toString()
{
return itemLabel;
}
}
}
You could create two new arrays in arrays.xml (list_items and list_item_activities)
Then, when an item is selected, you can use its index to find the associated activity.
<string-array name="list_items">
<item>ExampleActivity</item>
...
</string-array>
<string-array name="list_item_activities">
<item>com.example.app.ExampleActivity</item>
...
</string-array>
To explain a bit more, you would use the list_items to create the list:
String[] list = getResources().getStringArray("list_items");
for(int i = 0; i < list.length; i++){
// add the item
}
Then when the item is clicked:
public void onListItemClick(ListView l, View v, int position, long id){
String[] activities = getResources().getStringArray("list_item_activities");
// activities[position] is what you would use
}

Categories

Resources