Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How can I show a combobox in Android?
In android it is called a Spinner you can take a look at the tutorial here.
Hello, Spinner
And this is a very vague question, you should try to be more descriptive of your problem.
Here is an example of custom combobox in android:
package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
public class ComboBox extends LinearLayout {
private AutoCompleteTextView _text;
private ImageButton _button;
public ComboBox(Context context) {
super(context);
this.createChildControls(context);
}
public ComboBox(Context context, AttributeSet attrs) {
super(context, attrs);
this.createChildControls(context);
}
private void createChildControls(Context context) {
this.setOrientation(HORIZONTAL);
this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
_text = new AutoCompleteTextView(context);
_text.setSingleLine();
_text.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_NORMAL
| InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
| InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
| InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
_text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1));
_button = new ImageButton(context);
_button.setImageResource(android.R.drawable.arrow_down_float);
_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_text.showDropDown();
}
});
this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
/**
* Sets the source for DDLB suggestions.
* Cursor MUST be managed by supplier!!
* #param source Source of suggestions.
* #param column Which column from source to show.
*/
public void setSuggestionSource(Cursor source, String column) {
String[] from = new String[] { column };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
android.R.layout.simple_dropdown_item_1line, source, from, to);
// this is to ensure that when suggestion is selected
// it provides the value to the textbox
cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
_text.setAdapter(cursorAdapter);
}
/**
* Gets the text in the combo box.
*
* #return Text.
*/
public String getText() {
return _text.getText().toString();
}
/**
* Sets the text in combo box.
*/
public void setText(String text) {
_text.setText(text);
}
}
Hope it helps!!
Not tested, but the closer you can get seems to be is with AutoCompleteTextView. You can write an adapter wich ignores the filter functions. Something like:
class UnconditionalArrayAdapter<T> extends ArrayAdapter<T> {
final List<T> items;
public UnconditionalArrayAdapter(Context context, int textViewResourceId, List<T> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public Filter getFilter() {
return new NullFilter();
}
class NullFilter extends Filter {
protected Filter.FilterResults performFiltering(CharSequence constraint) {
final FilterResults results = new FilterResults();
results.values = items;
return results;
}
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
items.clear(); // `items` must be final, thus we need to copy the elements by hand.
for (Object item : (List) results.values) {
items.add((String) item);
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
... then in your onCreate:
String[] COUNTRIES = new String[] {"Belgium", "France", "Italy", "Germany"};
List<String> contriesList = Arrays.asList(COUNTRIES());
ArrayAdapter<String> adapter = new UnconditionalArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, contriesList);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.countries_list);
textView.setAdapter(adapter);
The code is not tested, there can be some features with the filtering method I did not consider, but there you have it, the basic principles to emulate a ComboBox with an AutoCompleteTextView.
Edit
Fixed NullFilter implementation.
We need access on the items, thus the constructor of the UnconditionalArrayAdapter needs to take a reference to a List (kind of a buffer).
You can also use e.g. adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>); and then use adapter.add("Luxemburg"), so you don't need to manage the buffer list.
The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.
I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.
Here is the screenshot of the final thing:
The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle". LinearLayout contains TextView with style="?android:attr/spinnerItemStyle". Complete XML snippet would be:
<com.example.comboboxtest.ComboBox
style="?android:attr/spinnerStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView"
style="?android:attr/spinnerItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:text="January"
android:textAlignment="inherit"
/>
</com.example.comboboxtest.ComboBox>
As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated 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="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter custom value ..." >
<requestFocus />
</EditText>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK"
/>
</LinearLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.
For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(
activity,
android.R.layout.simple_spinner_dropdown_item,
states
);
More or less, that should be it.
Custom made :)
you can use dropdown hori/vertical offset properties to position the list currently,
also try android:spinnerMode="dialog" it is cooler.
Layout
<LinearLayout
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<AutoCompleteTextView
android:layout_weight="1"
android:id="#+id/edit_ip"
android:text="default value"
android:layout_width="0dp"
android:layout_height= "wrap_content"/>
<Spinner
android:layout_marginRight="20dp"
android:layout_width="30dp"
android:layout_height="50dp"
android:id="#+id/spinner_ip"
android:spinnerMode="dropdown"
android:entries="#array/myarray"/>
</LinearLayout>
Java
//set auto complete
final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit_ip);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.myarray));
textView.setAdapter(adapter);
//set spinner
final Spinner spinner = (Spinner) findViewById(R.id.spinner_ip);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textView.setText(spinner.getSelectedItem().toString());
textView.dismissDropDown();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText(spinner.getSelectedItem().toString());
textView.dismissDropDown();
}
});
res/values/string
<string-array name="myarray">
<item>value1</item>
<item>value2</item>
</string-array>
Was that useful??
For a combobox (http://en.wikipedia.org/wiki/Combo_box) which allows free text input and has a dropdown listbox I used a AutoCompleteTextView as suggested by vbence.
I used the onClickListener to display the dropdown list box when the user selects the control.
I believe this resembles this kind of a combobox best.
private static final String[] STUFF = new String[] { "Thing 1", "Thing 2" };
public void onCreate(Bundle b) {
final AutoCompleteTextView view =
(AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);
view.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
view.showDropDown();
}
});
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line,
STUFF
);
view.setAdapter(adapter);
}
Related
Can I move the arrow somewhat closer to the text, in a easy way? Don't really understand the purpose of this as default when its transparent.
<Spinner
android:id="#+id/spinner_months"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
I have answered a similar question here: https://stackoverflow.com/a/42596698/1260126
This can be achieved by creating a custom layout for the selected spinner item custom_spinner_item.xml. I have added a TextView which displays the currently selected spinner item. The arrow icon is added in an ImageView. You can use any icon. The arrow icon moves depending on the length of the text. In fact you can completely modify the look of your spinner in this layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="#+id/spinner_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#mipmap/ic_arrow_down"/>
</LinearLayout>
Create a custom spinner adapter and inflate the above view. Also set the text of your selected spinner item from your list by overriding the default getView() method.
public class CustomSpinnerAdapter extends ArrayAdapter<String> {
LayoutInflater inflater;
List<String> spinnerItems;
public CustomSpinnerAdapter(Context applicationContext, int resource, List<String> spinnerItems) {
super(applicationContext, resource, spinnerItems);
this.spinnerItems = spinnerItems;
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.custom_spinner_item, null);
TextView type = (TextView) view.findViewById(R.id.spinner_item_text);
type.setText(spinnerItems.get(i));
return view;
}
}
Then instantiate the CustomSpinnerAdapter class and set it as your spinner's adapter. spinnerList is the list of items to be shown in the spinner.
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(getContext(), android.R.layout.simple_spinner_item, spinnerList);
spinner.setAdapter(customSpinnerAdapter);
I am not sure I am using the right words for this UI feature, but I have attached a snapshot of what I am looking to achieve in my app.
Its used by Go SMS, where a user types contacts in an edit text, after the user selects a contact from the completion drop down, the contact is inserted in the edit text as show in the attached image.The edit text is still open to accept further input.
For my app, I would like to do the grouping and insertion as soon as the user enters a comma, Just like the Tag input for StackOverflow works (But I believe I can handle that alone.) My problem is what kind of View is this or how do I modify an EditText to behave like this?
Thanks.
The official Chips library from Google (as used in Gmail, Email, Calendar, Messaging) is located at https://android.googlesource.com/platform/frameworks/opt/chips/
A simple example of how to use it can be found at https://code.google.com/p/platform-features-talk-io-2013/source/browse/src/com/example/iotalk/ChipsActivity.java
Two more Chips libraries.
Android Chips. Unlike some other this one is updated to have visuals reflecting the newly released "Material Design" standard.
Token Auto Complete. It is an Android Gmail style token auto-complete text field and filter.
Update:
Official way of doing it is now through Chips material component.
https://material.io/components/chips/
https://material.io/develop/android/components/chip/
https://medium.com/material-design-in-action/chips-material-components-for-android-46001664a40f
Old Answer:
You are looking for Chips library.
Here is one https://github.com/kpbird/chips-edittext-library
Another library that works with contacts by Roman Nurik https://plus.google.com/+RomanNurik/posts/WUd7GrfZfiZ
I think we can build our own chips view with Recycler view and Edit text or Auto complete text view. So we can customize it easily.
1. Created a tag shape say, tags_layout.xml in Drawable
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#cfcfcf">
</solid>
<corners android:radius="20dp">
</corners>
2. Created a layout for recycler view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="4dp"
android:gravity="center"
android:background="#drawable/tags_layout">
<TextView
android:id="#+id/tag_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:maxLength="25"
android:ellipsize="end"
android:padding="2dp"
android:text="Hello"/>
<ImageView
android:id="#+id/tag_closeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_close"/>
3. In our activity layout, we implement widgets recycler view just above edit text to keeping tags and edit text or Autocomplete text view to enter tags.
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/tagsRecyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
<EditText
android:id="#+id/tagsEditText"
android:inputType="text"
android:imeOptions="actionDone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
4. Created a model java class for recycler view
public class RecyclerModel {
private String tagText;
public RecyclerModel(String tagText){
this.tagText = tagText;
}
public String getTagText() {
return tagText;
}
public void setTagText(String tagText) {
this.tagText = tagText;
}
}
5. Adapter class for recycler view
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerAdapterHolder> {
Context context;
ArrayList<RecyclerModel> model = new ArrayList<>( );
public RecyclerAdapter(Context context,ArrayList<RecyclerModel> model){
this.context = context;
this.model = model;
}
#NonNull
#Override
public RecyclerAdapterHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_layout, parent, false);
return new RecyclerAdapterHolder(itemView);
}
#Override
public void onBindViewHolder(final RecyclerAdapterHolder holder, final int position) {
final RecyclerModel mod = model.get( position );
holder.tagTextView.setText( mod.getTagText() );
//remove tag on click x button
holder.tagImageView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
model.remove( position );
notifyDataSetChanged();
}
} );
}
#Override
public int getItemCount() {
return model.size();
}
public static class RecyclerAdapterHolder extends RecyclerView.ViewHolder {
public TextView tagTextView;
public ImageView tagImageView;
public RecyclerAdapterHolder(View itemView) {
super( itemView );
tagTextView = itemView.findViewById( R.id.tag_textView );
tagImageView = itemView.findViewById( R.id.tag_closeBtn );
}
}
}
6. Finally, In our activity, add data to recycler on entering data in edit text
public class MainActivity extends AppCompatActivity {
RecyclerView tagsRecyclerView;
EditText tagsEditText;
ArrayList<RecyclerModel> recyclerModels = new ArrayList<>( );
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
tagsRecyclerView = findViewById( R.id.tagsRecyclerView );
tagsEditText = findViewById( R.id.tagsEditText );
tagsEditText.setOnEditorActionListener( new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Toast.makeText( MainActivity.this,"hello",Toast.LENGTH_SHORT );
String str = tagsEditText.getText().toString();
if(str != null && !str.equals( "" )) {
getUpdateData( str );
tagsEditText.setText( null );
RecyclerAdapter adapter = new RecyclerAdapter( MainActivity.this, recyclerModels );
FlexboxLayoutManager gridLayout = new FlexboxLayoutManager( MainActivity.this );
tagsRecyclerView.setLayoutManager( gridLayout );
tagsRecyclerView.setAdapter( adapter );
}
}
return false;
}
} );
}
private void getUpdateData(String str) {
RecyclerModel model = new RecyclerModel( str );
recyclerModels.add( model );
}
}
7. Manifest file should contain gradles
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.google.android:flexbox:1.0.0'
there is a new library for Android Material Chips!
Starting from android support library version 28.0.0 Google added Chip view that allows us to display a chip view within our layout.
Design and documentation about Chip
And simple example:
<android.support.design.chip.ChipGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:chipSpacing="8dp">
<android.support.design.chip.Chip
android:id="#+id/some_chip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Chip Group"
app:chipIcon="#drawable/ic_android"
app:closeIconVisible="true" />
<android.support.design.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
app:chipIcon="#drawable/ic_android" />
<android.support.design.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chip"
app:chipIcon="#drawable/ic_android" />
<android.support.design.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Group"
app:chipIcon="#drawable/ic_android" />
</android.support.design.chip.ChipGroup>
A lot has changed. we have new libraries. I would recommend this library. It is very easy and powerful.
Simply add this dependency
implementation "com.hootsuite.android:nachos:1.1.1"
and this view
<com.hootsuite.nachos.NachoTextView
android:id="#+id/nacho_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:chipHorizontalSpacing="2dp"
app:chipBackground="#color/chip_background"
app:chipTextColor="#color/cheddar"
app:chipTextSize="16dp"
app:chipHeight="30dp"
app:chipVerticalSpacing="3dp"/>
and this adapter:
val suggestions = arrayOf("Tortilla Chips", "Melted Cheese", "Salsa", "Guacamole", "Mexico", "Jalapeno")
val adapter = ArrayAdapter(context, android.R.layout.simple_dropdown_item_1line, suggestions)
nachoTextView.setAdapter(adapter)
i have a trouble with listview. i added a checkbox into listview to choose items. my data is coming from sqlite so i use simple cursor adapter. length of my list is aproximatley 250 lines. i am clicking a check box.when i scroll down page (list), checkbox is clicked in every 10 lines.(for example in my screen show 10 lines data when i scroll 11th lines, this row's checkbox had clicked. how can i solve this problem.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/checkBox"
android:textStyle="bold"
android:text="TextView" />
<TextView
android:id="#+id/nick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/nick"
android:layout_alignBottom="#+id/nick"
android:layout_alignParentRight="true"
android:text="TextView" />
<TextView
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:layout_toRightOf="#+id/checkBox"
android:text="TextView" />
</RelativeLayout>
and this is source code
package com.example.myprojects;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class send_message extends Activity {
private ListView list;
private EditText search;
SimpleCursorAdapter adapterx;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendmessage);
list=(ListView)findViewById(R.id.list);
search=(EditText)findViewById(R.id.search);
loadfromdatabase();
}
private void loadfromdatabase() {
mydb info=new mydb(this);
info.open_read();
Cursor c = info.getAllData();
String[] columns = new String[] {mydb.KEY_NAME,mydb.KEY_PHONE, mydb.KEY_NICK};
int[] to = new int[] {R.id.name,R.id.phone, R.id.nick };
#SuppressWarnings("deprecation")
SimpleCursorAdapter adapter= new SimpleCursorAdapter(this, R.layout.activity_sendmesage_rows, c, columns, to,0);
list.setAdapter(adapter);
info.close();
}
}
If you have CheckBoxes in ListView you have problem, because ListView reuses Views that aren't already visible on screen. That's why when you scroll down, it loads (a few times) that one CheckBox that was checked by you previously. So you can't rely on default CheckBox's behaviour. What you need is:
Prevent user from checking CheckBox. You can do this by calling cb.setEnabled(false), where cb is CheckBox which you are using.
Create your own adapter class that will extend SimpleCursorAdapter. In this class you will store list of indexes of items that are checked.
Override getView() method in your adapter class and there manually set CheckBox to be checked if it's position is stored in checked items array.
Create OnClickListener for your ListView which will take care of adding/removing checked items' positions from adapter's internal array.
Edit:
This would be the code of your adapter:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
public ArrayList<Integer> mItemsChecked;
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
mItemsChecked = new ArrayList<Integer>();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
for(int i = 0; i < mItemsChecked.size(); i++) {
if(mItemsChecked.get(i) == position) {
CheckBox cb = (CheckBox)convertView.findViewById(R.id.checkBox1); // Instead of checkBox1, write your name of CheckBox
cb.setChecked(true);
}
}
return super.getView(position, convertView, parent);
}
/* Just a handy method that will be responsible for adding/removing
items' positions from mItemsChecked list */
public void itemClicked(int position) {
for(int i = 0; i < mItemsChecked.size(); i++) {
if(mItemsChecked.get(i) == position) {
mItemsChecked.remove(i);
return;
}
}
mItemsChecked.add(position);
}
}
This is OnItemClickListener for your ListView:
final ListView lv = (ListView)findViewById(R.id.listView1); // Your ListView name
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
((MySimpleCursorAdapter)lv.getAdapter()).itemClicked(position);
lv.getAdapter().notifyDataSetChanged(); // Because we need to call getView() method for all visible items in ListView, so that they are updated
}
});
Just remember to disable your CheckBox so that user can't click it.
Now you can see it as a little hack, because user doesn't click CheckBox at all - application sees it as clicking in specific ListView item, which in turn automatically checks appropriate CheckBox for you.
Here is simple example that will help you to implement that scenario
http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html
I'm using a custom listview I found here:
http://developer.android.com/resources/samples/ApiDemos/res/layout/linear_layout_9.html
Seems to be valid in Eclipse, and looks good in the preview tab. It's just a listview that has a button on the bottom. So i've added it as R.layout.buttonlist
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/testbutton"
android:text="#string/hello" android:layout_alignParentBottom="true" />
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/list"
android:layout_alignParentTop="true" android:layout_above="#id/testbutton" />
</RelativeLayout>
Unfortunately when I run it, i get a pop up window that says Android has closed unexpecitdly:
setListAdapter(new ArrayAdapter<String>(this, R.layout.buttonlist , data));
When I try using a built in list view:
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data));
everything works fine. I dont see any errors or warnings in logcat, so I'm not sure how to pinpoint the problem. Does anyone have any ideas? Thanks
Edit: adding activity
public class TestActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<String> data = new ArrayList<String>();
data.add("hello");
data.add("world");
setContentView(R.layout.buttonlist);
//setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data));
}
}
Hoofamon, I would like to correct you here. You are not creating a custom ListView but a custom layout with a ListView. Also, I believe that you have not completely understood what the setListAdapter is doing here.
This line that you have is telling the listview to consume 'android.R.layout.simple_list_item_1' as the content of its layout. This layout comes pre-defined in the Android SDK. It would just contain text in each item of a listview. The third attribute 'data' indicates the content of each listview item.
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data));
So, as Mike L. has suggested, if your intent is to have a listview with only text (having the default format), then the line above would serve the purpose well. You can set 'R.layout.buttonlist' as the layout of your activity using
setContentView(R.layout.buttonlist);
However, if you are planning to include additional content in the listview (read images) or want to change the styling of the text, you would have to define a custom layout for the listview. We can direct you to appropriate sources if you want to know how that can be done.
EDIT: A possible way of loading data into a normal ListView
TestActivity.java
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonlist);
List<String> data = new ArrayList<String>();
data.add("hello");
data.add("world");
ListView mListView = (ListView)findViewById(R.id.list);
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data));
}
}
buttonlist.xml
<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/testbutton"
android:text="#string/hello"
android:layout_alignParentBottom="true" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list"
android:layout_alignParentTop="true"
android:layout_above="#+id/testbutton" />
</RelativeLayout>
This is how it should look like on the emulator:
I don't think you can have a listview in the layout of an adapter. The passed in layout should just describe a row in the listview. So buttonlist should just contain the xml for the button. The listview needs to be in a separate layout file. If this is a list activity then you don't need another layout file, just call setListAdapter like you are doing.
If you want to use your R.layout.buttonlist to fill up your listview,you can do it as follows(your TestActivity should extend Activity,not ListActivity):
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonlist);
String data[]=new String[]{"Item_1","Item_2","Item_3"}
Button b=(Button)findViewById(R.id.testbutton);
ListView lv=(ListView)findViewById(R.id.list);
ArrayAdapter aa=new ArrayAdapter(context,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
//Your code...
}
Now if you want to create custom listitem to be displayed in the listview,then you need to do like this:
Create your custom listitem xml file.
Ex: custom_listitem.xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/icon"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="#+id/text"
/>
Create custom ArrayAdapter:
Ex. CustomArrayAdapter.class
public class CustomArrayAdapter extends ArrayAdapter<String> {
String[] array;
LayoutInflater mInflater;
public CustomArrayAdapter(Context context, int textViewResourceId,
String[] objects)
{
super(context, textViewResourceId, objects);
array=objects;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.custom_listitem, null);
holder = new ViewHolder();
holder.text=(TextView)convertView.findViewById(R.id.text);
holder.img=(ImageView)convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.text.setText(array[position]);
if(position==0)
holder.img.setImageResource(R.drawable.img1);
else if(position==1)
holder.img.setImageResource(R.drawable.img2);
else if(position==2)
holder.img.setImageResource(R.drawable.img3);
return convertView;
}
static class ViewHolder
{
TextView text;
ImageView img;
}
}
Use this custom adapter class in your main activity to fill up listview:
Be sure,this main activity extends Activity and not ListActivity
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context=getApplicationContext();
lv=(ListView)findViewById(R.id.listview);
CustomArrayAdapter aa=new CustomArrayAdapter(context,R.layout.custom_listitem, new String[]{"item_1","item_2","item_3"});
lv.setAdapter(aa);
// other lines of code
.
.
.
The requirement for my screen is like having a title bar at the top middle and followed by the list view when am trying to do that am not able to do like i got state name in every list item.I want that only in the top and once. And the screen shot of it is
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000000"
android:text="Select State"
></TextView>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="#+id/label"
android:textSize="30px"></TextView>
</TableRow>
</TableLayout>
I have tried many ways this is my present layout
and my java code is
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 new21 extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Andhra Pradesh", "Kerala","Tamilnadu","Karnataka" };
// Use your own layout and point the adapter to the UI elements which
// contains the label
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.new21,
R.id.label, names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
if(keyword.equals("Andhra Pradesh"))
{
Intent ima45=new Intent(new21.this,new31.class);
startActivity(ima45);
}
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
Can any one help me.
You can addHeader to the ListView like this,
View header = getLayoutInflater().inflate(R.layout.header, null);
ListView listView = getListView();
listView.addHeaderView(header);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, names));
Where R.layout.header is the layout that contains a TextView with text "Select State"
UPDATED:
public class ListViewProblemActivity extends ListActivity {
ListView listView;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Andhra Pradesh", "Kerala","Tamilnadu","Karnataka" };
// Use your own layout and point the adapter to the UI elements which
// contains the label
TextView tv = new TextView(getApplicationContext());
tv.setText("Select State");
listView = getListView();
listView.addHeaderView(tv);
this.setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
if(position != 0){
System.out.println(position - 1);
Object o = this.getListAdapter().getItem(position - 1);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
}
Usey only a ListView in your activity, remove the heading there. Then use ListView.addHeaderViwe(); to add a header to the Listview. This Header is display before the first item.
See the documentaton for further information.
you better use ListView.addHeaderViwe();
but don't forget to remove what u did "extends ListActivity", no need for that,
and also remove title from your "new21.xml"
in your xml, just fix the text item u want to show in every row of the list,
You are doing fully wrong. Just take a LinearLayout with one TextView (for Title bar) and ListView (To display listview), nothing more than these 2 views.
<?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">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000000"
android:text="Select State">
</TextView>
<ListView
android:id="#+id/lviewState"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
Now, follow your code to display ListView.