Make individual onClick() methods for children of expandablelistview - android

I have an expandablelistview as shown below. I've made it so that a toast message will pop up when each child is clicked. I need each of the children to start their own activity/fragment, which required individual onClick() methods. Does anybody know how this can be achieved? Thanks. NOTE: I am using SimonVT's slidingmenu library and I'm pretty new to android programming.
MainActivity.java:
package press.linx.expandablelistdemo;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xml.sax.SAXException;
import net.simonvt.menudrawer.MenuDrawer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListView exv;
MenuDrawer mDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDrawer = MenuDrawer.attach(this);
mDrawer.setContentView(R.layout.activity_main);
mDrawer.setMenuView(R.layout.leftmenu);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
exv.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
String itemclicked = MyAdapter.childList[groupPosition][childPosition];
Toast.makeText(getApplicationContext(), "you clicked " + itemclicked, Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void setListAdapter(SimpleAdapter adapter) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MyAdapter.java
package press.linx.expandablelistdemo;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter {
private Context context;
Typeface typeface;
String []parentList = {"Tech", "Best Of", "Art & Design", "Other"};
static String [][] childList = {
{
"All Tech", "Reviews", "Gaming", "Gadgets"
},
{
"Android"
},
{
"Architecture"
},
{
"Infographics"
}
};
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getChildId(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
//typeface = Typeface.createFromAsset(context.getAssets(), "font/robotochild.ttf");
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(30, 10, 0, 10);
tv.setTextSize(15);
//tv.setTypeface(typeface);
tv.setTextColor(Color.WHITE);
return tv;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView tv = new TextView(context);
typeface = Typeface.createFromAsset(context.getAssets(), "font/roboto.ttf");
tv.setText(parentList[groupPosition]);
tv.setPadding(50, 10, 0, 10);
tv.setTextSize(20);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface);
return tv;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
menulistview.xml
<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"
android:background="#drawable/geowall">
<ExpandableListView
android:id="#+id/expandableListView1"
android:groupIndicator="#null"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="3dp" >
</ExpandableListView>
!

If you want differing functionalities per button, consider storing them as the buttons' tag property (in the XML layout). The View v parameter in your onChildClick listener is the View of the child being clicked; it can then be used to retrieve the tag, like so:
v.getTag();
You could either have a switch-case block to call the correct activity based on the tag, or store the exact name of the activity in the tag and pass that in via reflection to retrieve the class for the activity. Alternatively, you could store a HashMap mapping the tag-names to Activity classes/variables.

This might be you are looking for.
Let’s get start by creating a project in Eclipse IDE.
Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as AndroidListViewActivity.
Once the project is created open your main activity java file (in this case AndroidListViewActivity.java) and extend the class from ListActivity.
public class AndroidListViewActivity extends ListActivity {
3. Now we need a string resources file to store all list item labels. So create an XML file under values folder and name it as list_data.xml and paste the following code.
( Right Click on res/values ⇒ New ⇒ Android XML File)
list_data.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="adobe_products">
<item>Adobe After Effects</item>
<item>Adobe Bridge</item>
<item>Adobe Dreamweaver</item>
<item>Adobe Edge</item>
<item>Adobe Fireworks</item>
<item>Adobe Flash</item>
<item>Adobe Photoshop</item>
<item>Adobe Premiere</item>
<item>Adobe Reader</item>
<item>Adobe Illustrator</item>
</string-array>
</resources>
In ListView each list item will be an xml layout, so we can customize each list item. Create an XML file under res/layout folder and name it as list_item.xml and type the following code. This xml layout will be single list item row.
( Right Click on res/layout ⇒ New ⇒ Android XML File)
Now open your main activity java file (AndroidListViewActivity.java) and type the following code. In the following code i am importing all xml resources data and storing them in an Array. On the next step i am binding array to ListAdapter.
AndroidListViewActivity.java
package com.androidhive.androidlistview;
import android.app.ListActivity;
import android.content.Intent;
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;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
}
}
Now run your project you can see listview with list of array items. But on clicking single list item you can see no action. So we need to start new activity on selecting single list item.
Launching new Activity on selecting single list item
In my previous article i had explained how to switch between screens. Here i am going to show single list item details in new screen.
Now create new activity class under src folder. Right Click on src/package folder ⇒ New ⇒ Class and name it as SingleListItem. (SingleListItem.java)
Open your AndroidListViewActivity.java and modify the code to following. In the following code i am getting the selected list item string(product name) and sending it to new Activity.
AndroidListViewActivity.java
package com.androidhive.androidlistview;
import android.app.ListActivity;
import android.content.Intent;
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;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
}
});
}
}
Now in new activity we need to display the received from listview activity.
Create a new xml file under res/layout and name it as single_list_item_view.xml and type the following code. This XML file will be layout for SingleListItem.java
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
Now open your second activity file i.e SingleListItem.java and paste the following code.
SingleListItem.java
package com.androidhive.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
The final step is to add an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.androidlistview"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidListViewActivity"
android:label="Android List View">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.

Related

How to fetch data from a custom list view with multiple radio buttons

I have gone through a lot of links here, but yet i was not able to get my stuff working. Can you please help me fetch data from my custom list.
Details are as under :- My custom list view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RadioGroup
android:id="#+id/radioGroup_option"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"/>
<RadioButton
android:id="#+id/rb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="#+id/rb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
I am populating a List through the UI the code for that is :-
package com.example.customadapter;
import java.lang.reflect.Array;
import java.util.Arrays;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CustomAdapter extends ActionBarActivity {
AddDataToArray mydata;
EditText qstno,qstn,opt1,opt2;
Button btn_save,btn_display;
int questio_no;
String question,option1,option2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_adapter);
mydata=AddDataToArray.getInstance();
qstno=(EditText)findViewById(R.id.edt_qstn_no);
qstn=(EditText)findViewById(R.id.edt_add_qstn);
opt1=(EditText)findViewById(R.id.edt_opt1);
opt2=(EditText)findViewById(R.id.edt_opt2);
btn_save=(Button)findViewById(R.id.btn_save);
btn_display=(Button)findViewById(R.id.btn_display);
btn_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
questio_no=Integer.parseInt(qstno.getText().toString());
question=qstn.getText().toString();
option1=opt1.getText().toString();
option2=opt2.getText().toString();
System.out.println("Questio added in the UI --> "+ question);
String statusReceived=mydata.AddingQuestions(questio_no, question, option1, option2);
Toast.makeText(getApplicationContext(), statusReceived, Toast.LENGTH_LONG).show();
qstn.setText("");
opt1.setText("");
opt2.setText("");
}
});
btn_display.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i=0;i<mydata.myQstnList.size();i++)
{
System.out.println("Qustion no"+mydata.myQstnList.get(i).getQstno());
System.out.println("Question -->"+mydata.myQstnList.get(i).getQstn());
//System.out.println("The First Option added was:-" + mydata.myQstnList.get(i).getOpt1());
}
Intent myIntent = new Intent(CustomAdapter.this, Mediator.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.custom_adapter, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Finally i made an adapter from base adapter as follows:-
package com.example.customadapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Question> mQuestion;
Context context;
public MyAdapter(Context context,List<Question> mQuestion) {
super();
this.context=context;
this.mQuestion = mQuestion;
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mQuestion.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mQuestion.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
ViewHolder holder;
if (convertView == null){
view = mInflater.inflate(R.layout.customized_view, parent,false);
holder = new ViewHolder();
holder.rg=(RadioGroup)view.findViewById(R.id.radioGroup_option);
holder.tv_qstn=(TextView)view.findViewById(R.id.tv_id);
holder.rb_opt1=(RadioButton)view.findViewById(R.id.rb_1);
holder.rb_opt2=(RadioButton)view.findViewById(R.id.rb_2);
view.setTag(mQuestion);
}else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
Question qstnRef=mQuestion.get(position);
holder.tv_qstn.setText(qstnRef.getQstn());
holder.rb_opt1.setText(qstnRef.getOpt1());
holder.rb_opt2.setText(qstnRef.getOpt2());
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//List<Question> data =(List<Question>) group.getTag();
//Toast.makeText(context,(CharSequence) data.get(checkedId).getOpt2(),Toast.LENGTH_SHORT).show();
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
RadioButton r_btn=(RadioButton)group.getChildAt(i);
if (r_btn.getId() == checkedId){
System.out.println(r_btn.getText().toString());
}
}
}
});
return view;
}
private class ViewHolder {
public TextView tv_qstn;
public RadioButton rb_opt1,rb_opt2;
public RadioGroup rg;
}
}
But i am trying to get this data that i enter in the UI, but I am not able to get this to work, please provide me assistance !!!!
The code in the current format is giving me runtime error :-
05-09 06:01:06.669: E/AndroidRuntime(2420):
java.lang.ClassCastException: android.widget.TextView cannot be cast
to android.widget.RadioButton
05-09 06:01:06.669: E/AndroidRuntime(2420): at
com.example.customadapter.MyAdapter$1.onCheckedChanged(MyAdapter.java:83)
group.getChildCount() returns 3 as it has 3 child. but 1 child is of TextView that's why you were getting java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton
To avoid it do type checking using instanceof before typecasting.
do like this:
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
if(group.getChildAt(i) instanceof RadioButton ) { // check if child is `RadioButton`
RadioButton r_btn = (RadioButton) group.getChildAt(i);
if (r_btn.getId() == checkedId) {
System.out.println(r_btn.getText().toString());
}
}
}

Using few ListView's in one activity and layout

I'm trying to organize data recieved by SMS messages in specified ListView's.
I tried to create and activity which will contain 3 ListView's in one layout.
But, while running the activity it crashes.
Can someone help with this?
Here is the XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ListView
android:id="#+id/idList"
android:layout_width="112dp"
android:layout_height="384dp"
android:layout_gravity="center" >
</ListView>
<ListView
android:id="#+id/namesList"
android:layout_width="96dp"
android:layout_height="387dp"
android:layout_gravity="center" >
</ListView>
<ListView
android:id="#+id/phonesList"
android:layout_width="wrap_content"
android:layout_height="382dp"
android:layout_gravity="center" >
</ListView>
</LinearLayout>
And here is the activity code:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DataLists extends ListActivity implements OnClickListener {
ListView idList, namesList, phonesList;
MyReciever mr;
ArrayList<String>ids= new ArrayList<String>();
ArrayList<String>names=new ArrayList<String>();
ArrayList<String>phones=new ArrayList<String>();
ArrayAdapter<String> idAdapter, namesAdapter, phonesAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details_lists);
idList=(ListView)findViewById(R.id.idList);
namesList=(ListView)findViewById(R.id.namesList);
phonesList=(ListView)findViewById(R.id.phonesList);
idAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,ids );
idList.setAdapter(idAdapter);
namesAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
namesList.setAdapter(namesAdapter);
phonesAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, phones);
phonesList.setAdapter(phonesAdapter);
}
public void addItemToIdList(String st)
{
ids.add(st);
idAdapter.notifyDataSetChanged();
}
public void addItemToNamesList(String st)
{
names.add(st);
namesAdapter.notifyDataSetChanged();
}
public void addItemToPhonesList(String st)
{
phones.add(st);
phonesAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private class MyReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle=intent.getExtras();
SmsMessage[]msgs=null;
if(bundle!=null)
{
Object[]pdus=(Object[]) bundle.get("pdus");
msgs=new SmsMessage[pdus.length];
for(int i=0;i<msgs.length;i++)
{
int index=0, prev=0;
String msgBody=msgs[i].getMessageBody().toString();
index=msgBody.indexOf(';');
prev=index;
String name=msgBody.substring(0, index);
addItemToNamesList(name);
msgBody=msgBody.substring(index+1);
index=msgBody.indexOf(';');
String id=msgBody.substring(prev, index);
addItemToIdList(id);
msgBody=msgBody.substring(index+1);
String phone=msgBody;
addItemToPhonesList(phone);
}
}
}
}
}
You have extended ListActivity. This is a convenience class that can be used to display a single ListView. The crash is clearly described in your logcat/stacktrace:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
Since your layout contains 3 ListViews, you probably can't use ListActivity anyway. Just change your activity to extend Activity and go from there.

Creating ArrayAdapter using xml resource and retrieving "id" or "value" fields using spinner

I am trying to create a spinner, the values of which I am populating from a resource xml, using ArrayAdapter.
I also want to give the resource items some "id" or "value". How can i retrieve these values inside the onItemSelected() callback ?
Here is the Java code.
package com.waus.waus;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class Register extends Activity implements OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Spinner countrySpinner = (Spinner) findViewById(R.id.country_code_spinner);
ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(this, R.array.country_codes, android.R.layout.simple_spinner_item);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySpinner.setOnItemSelectedListener(this);
countrySpinner.setAdapter(countryAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(this, "THIS IS WHERE I WANT TO SHOW THE ID/VALUE" ,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This is the XML file I want to use.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country_codes">
<item value="91">India</item>
<item value="1">United States</item>
// OR
<item id="1">United States</item>
</string-array>
</resources>
How can it be done without using 2 resource files. i.e. one for codes and another for names.
String[] SortByField= activity.getResources().getStringArray(
R.array.country_codes);
or
Arrayadapter adapterFillClass = ArrayAdapter.createFromResource(activity,
R.array.country_codes,
android.R.layout.simple_spinner_dropdown_item);
spinner.setadapter(adapterFillClass);
i hope it useful to you.

Android Listview Search filter

I am trying to make a list view search for Android. I have found many tutorials that do just that where
a search-bar is placed at the top and if you type in the box the results get filtered.
In my app I want to click on given items after filtering has been completed, I have implemented setOnItemClickListener. The issue is that after filtering the position of each class that I want to open changes and the incorrect pages open. I was unable to find a solution....
Here is the jave code:
package com.equations.search;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class EquationsSearch extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.equations_search);
// Listview Data
final String products[] = { "Dell Inspiron", "HTC One X",
"HTC Wildfire S", "HTC Sense", "HTC Sensation XE" };
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this,
R.layout.equations_search_list, R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
EquationsSearch.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChange(Editable arg0) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// if(position == 1)
String openClass = products[position];
if (openClass.equals("HTC Wildfire S")) {
// code specific to first list item
Intent myIntent = new Intent(view.getContext(), A6262.class);
startActivityForResult(myIntent, 0);
}
}
});
}
}
and here is the xml equations_search.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Editext for Search -->
<EditText android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="textVisiblePassword"/>
<!-- List View -->
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and equations_search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/product_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
Thank you in advance.
Rather than products[position], use adapter.getItem(position). When the ListView is not in filter mode, those two things will be the same. But, in filter mode, getItem() will take the filtering into account.
The ListAdapter will change the relative position of the items it currently shows due to the filtering. You should always use getItem(position) to retrieve the correct item.

How to link listView to another class when list item is selected?

Hi I am trying to make an app that shows a list of items using listView and when the user select one of the items from the list. the app will call the specific class that is link to the item selected however i encountered an error at the second #override, saying that the override must override a super class. Here are my codes for class and xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/botanicgate" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package com.fyp.gulliver;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends ListActivity{
/** Called when the activity is first created. */
String places[] = {"BotanicGarden", "Sentosa"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotspot);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter
(HotSpot.this, android.R.layout.simple_list_item_1,
places));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Class ourClass;
String item = ((TextView)view).getText().toString();
try {
ourClass = Class.forName
("com.fyp.gulliver." + item);
Intent ourIntent = new Intent(HotSpot.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
As i am still new to android, thus i do not know what mistakes i have made, I will be grateful if another one can help me to solve my error thank you :D
Try changing this:
listView.setOnItemClickListener(new OnItemClickListener();
to
listView.setOnItemClickListener(new AdapterView.OnItemClickListener();
and remove the 2nd #Override

Categories

Resources