My application consists of 2 activities.The first activity contains a TextView,if you click on it, you move to the second activity that consists of a ListView and a button Done. The ListView contains TextViews with a CheckBox. If you click on button then it finish activity and returns selected text item. If you go back to the list view the selected checkboxes restored.
Code would be appreciated.
First of all I suggest you to use CheckedTextView control instead of a CheckBox & TextView. CheckedTextView serves as the combination of checkbox and textview and is easy to handle and implement.
Secondly, you should have an ArrayList of boolean of the exact size as the ListView no. of Items. Then you can set the ArrayList items accordingly in the OnListItemClick function of ListView. At any time and anywahere in your code, you can get the reference of your selection of the ListView. Its simple and efficient.
Here is a sample OnListItemClick code:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
arrCheckBox.set(position, !arrCheckBox.get(position));
CheckedTextView ctvListItem = (CheckedTextView)v.findViewById(R.id.ctvCustomLVRowID);
ctvListItem.setChecked(arrCheckBox.get(position));
}
Here arrCheckBox is a boolean ArrayList which is keeping record of our selection and size of this array is same as no. of ListItems. I hope now you can figure it out.
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView android:id="#+id/ListView01" android:layout_height="wrap_content"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
Java code:
public class ListViewMultipleChoiceExample extends Activity {
private ListView lView;
private String lv_items[] = { "Android", "iPhone", "BlackBerry",
"AndroidPeople", "J2ME", "Listview", "ArrayAdapter", "ListItem",
"Us", "UK", "India" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
Related
I want to create a language selector for my app. I created a button in the menu layout and I want a spinner to open when one of option menu is clicked . I'm a beginner so I'd love if you could explain your answers.
first you have to create an xml layout where your spinner element will be placed
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="Select Language"
/>
</LinearLayout>
then i your activity where you would like to show the snipper you should implement OnItemSelectedListener interface for handling the selections of the spinner
public class SnipperActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here you get the reference to the spinner element declared in your xml layout
Spinner spinner = (Spinner) findViewById(R.id.spinner);
//set the listener to the spinner
spinner.setOnItemSelectedListener(this);
//here you create an arraylist for the items to be displayed in your spinner element
List<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("Greek");
}
//define an adapter for the spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, languages);
//set the style of the snipper, in this case a listview with a radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it em);
//attach the adapter to your spinner element
spinner.setAdapter(dataAdapter);
}
to handle spinner elements selection you have to ovveride the following method inside SnipperActivity class
#Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
// On selecting a spinner item
String language = parent.getItemAtPosition(position).toString();
//show a spinner item
Log.e("TAG", "Spinner item selected " + language);
}
Have a look at this article on creating custom dialogs:
http://android-developers.blogspot.co.uk/2012/05/using-dialogfragments.html
IMHO spinners are not very flexible. I'd use a listview in my dialog if I were you, but that choice is yours :)
I am fairly new to Android programming and trying to set items in a listview upon loading the information from internal storage.
I have two global arrays that I am using: first one is a String array that has the names of the items in the list, and the second is a boolean array that keeps track of which items are crossed out. I am using a TextView in the listview.
main_activity.xml:
<ListView
android:id="#+id/listViewMyList"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
rowlayout.xml:
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:text="#+id/label" />
I have created an onClickListener() which successfully updates the state of each list item:
public class MainActivity extends Activity
{
// Initialize the list (global list values)
String[] values = new String[0]; // array of items for the list
boolean[] checkedVals = new boolean[0]; // keep track of which items are crossed-off
String localFileName = "myListData.csv";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// read the data from file if present
readListFromFile();
// find the ListView
ListView lst = (ListView) findViewById(R.id.listViewMyList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, values);
lst.setAdapter(adapter);
// define what happens on click
lst.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// read crossed status and set text flags for strikethrough
if (checkedVals[position])
{
TextView text1 = (TextView)view.findViewById(R.id.label);
text1.setPaintFlags(text1.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
text1.setTextColor(0xff000000);
checkedVals[position] = false;
}
else
{
TextView text1 = (TextView)view.findViewById(R.id.label);
text1.setPaintFlags(text1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
text1.setTextColor(0xff888888);
checkedVals[position] = true;
}
// save the data in a file
saveListToFile();
}
});
}
So this code works fine for crossing out and un-crossing out the items. I don't know how can I cross-out some of the items (determined by the checkedVals boolean array) without clicking or any activity when I load the list.
Thanks in advance.
You need to create a custom Adapter by extending ArrayAdapter and overriding getView().
The getView() method loads every row's layout, this is where you should check if the row is in your checkedVals array and draw with the appropriate flags. This Google Talk by an Android lead programmer, Romain Guy, provide a wealth of information about best practices on how to do this.
Below is my code and image. I am populating the listview with the arraylist in runOnUIThread() in onpostexecute() which has values gotten from the remote server in the doInBackground(). But the thing is elements are visible only when the focus is on particular item. I have been trying with different things to set the elements visible, but all have gone vain. Can someone please suggest me how to get the items visible. Note: I can't extend the ListActivity, as I have another class that needs to be extended which is the subclass of an activity.
runOnUiThread(new Runnable() {
public void run() {
//Updating parsed json data to Listview
ListView listView = (ListView)findViewById(R.id.listsubcategory);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, subCategoryList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selectedSubcategory = subCategoryList.get(position);
Toast.makeText(getApplicationContext(), "You clicked on "+selectedSubcategory, Toast.LENGTH_SHORT).show();
}
});
}
});
The problem is the styling of the list items. In normal state your items have white background and white text color, therefore you can't see them. When the state changes to focused the colors change. You can easily solve the problem by using your custom list item instead of the system's android.R.layout.simple_list_item_1.
Define a layout for the item, it can be something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/my_item_background"
android:textColor="#color/my_text_color"
/>
Now, if the item's layout is res/layout/my_list_item.xml, create the adapter this way:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),
R.layout.my_list_item, subCategoryList);
My goal is to make a ListView of each row of which contains one single button which occupies the entire space in each row. Below is the code where the onItemClick method does not work.Does anyone have idea why it does not work?
I have next class Activity:
public class MyActivity extends Activity implements OnItemClickListener {
public void onCreate(Bundle savedInstanceState) {
//
//Here is a lot of code..
//.....
List<String> items = new ArrayList<String>();
ListView lv = (ListView) findViewById(R.id.listView);
if (result.getItems().size() > 0) {
// Init list view
lv.setVisibility(lv.VISIBLE);
lv.setTextFilterEnabled(true);
lv.setAdapter(new buttonAdapter(this, R.layout.list_item,
items));
lv.setOnItemClickListener(this);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
//....
}
}
And here is my XML-element for each row in the ListView:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item_button"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textStyle="bold"
android:textSize="16sp">
</Button>
onItemClick only fires when the item itself is clicked. If you had a TextView or a TextView and an ImageView instead of a Button, clicking the item then will trigger onItemClick.
If you want to respond to a button click, you can set up an onClickListener for each button in the adapter. Then use the view references passed to the listener to distinguish between items.
However, if you do want the onItemClick to be triggered, you will need to add the property
android:descendantFocusability="beforeDescendants"
to the ListView tag in the layout XML.
This lets the ListView handle the click first.
As to why you want a button that fills an entire listitem instead of letting the listitem be clickable itself, that still doesn't quite make sense. You should do one or the other, since whatever you do, only one of them will actually be clicked.
If the button you want to place on the listview item occupies the whole item width and height the onItemClickListener will not be envoked since there is no content space to click/touch. You can implement the onClickListener() (or onTouchListener()) for the button. But why button, you can do the same without button but just with click on the listview item as it is.
I want to know how to open another ListView after one of rows on the previous ListView has been clicked?
Bee VOA reader could be a good example to see what I'm talking about.
List A List B
DeskTop Development ---> Buttons
TextView
ScrollBar
Mobile
Graphic
Game
So there is one list A on the phone's screen, and there are many topics in the list A
If I clicked on one of the topic,let's say DeskTop Development, then the whole ListView
will be slided away from the screen and the new List B will be presented.
So how to implement it?
Opening a new Activity while passing the appropriate data to display the correct information is a good way to do what you're doing. This is a code example of a list of states which goes to a list of cities in the selected state from the previous list. The state listview from the first activity sends the name of the state to the city listview in second activity which displays a list of cities from that state.
private ListView lv;
setContentView(R.layout.displaylayout);
lv = (ListView)findViewById(R.id.DisplayList);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(), DisplayLocationsCities.class);
myIntent.putExtra("state",lv.getItemAtPosition(position).toString());
startActivityForResult(myIntent, 0);
}
});
//////////////////////back button code allowing you to go back to the previous list (close anything that need to be closed in onDestroy()):
this.backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// equivalent of 'return'
finish();
}
});
//////////////////////adding items to your list dynamically:
String [] list = {"New York","Illinois","California","Wisconsin"};
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, list));
//////////////////////Extra Credit: Layout for each listView item - R.layout.list_item (list_item.xml in the res/layout folder):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:cacheColorHint="#android:color/transparent"
android:textSize="12sp" android:textColor="#000000" android:textStyle="bold" android:gravity="center">
</TextView>
Implement the onListItemClick() method so that on click it starts a new ListActivity. This way the navigation in the menu will be easier as you will be able to use the back button.