Setting font on ListActivity in Android - android

I'm trying to set a custom font on a list activity in Android. I can successfully do it once an item gets clicked, like so:
#Override
protected void onListItemClick(ListView listView, View listItemView,
int position, long id) {
int childCount = listView.getChildCount();
for (int i = 0; i < childCount; i++) {
TextView c = (TextView) listView.getChildAt(i);
c.setTypeface(mTypeFace);
}
However, before the item is clicked, assigning a font has no impact:
//
// Create the adapter to display the choice list
//
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.simple_list_item_single_choice_custom,
mAppState.mAnswerArray) {
};
/* attach the adapter to the ListView */
setListAdapter(adapter);
ListView v = getListView();
int childCount = v.getChildCount();
for (int i = 0; i < childCount; i++) {
TextView c = (TextView) v.getChildAt(i);
c.setTypeface(mTypeFace);
}
Debugging show that in the initial setup, the ListView v has zero children, despite the fact they show up in the GUI and mAnswerArray has the children.
Any idea what the problem might be?

Set the viewBinder and override the setViewValue in your adapter, like so:
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(columnIndex == 7){
TextView textView = (TextView) view;
textView.setTypeface(gotham_book);
}
}
}

Related

How to repeat spinner dynamically?

I have RelativeLayout with ScrollView as the root element. In RecyclerView I have spinner and TextView. Now I am getting data from JSON like RollNumber and Marks. Now in TextView, I need to show RollNumber and in Spinner Marks should be displayed. I already got the data in ArrayList<Progress> and what should be the code will look like for this situation;
Do I have to repeat the RelativeLayout in for loop?
OnCreate
for (int i = 0; i < progress.size(); i++) {
progress_addmore_spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
loadspinner
}
private void loadSpinners()
{
if (progress != null || progress.size() > 0) {
ArrayList<String> progresscard = new ArrayList<>();
for (int i = 0; i < progress.size(); i++) {
progresscard.add(progress.get(i).toString());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
progresscard);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
progress_addmore_spinner.setAdapter(dataAdapter);
if (progress.get(0).getMarks() != null && !progress.get(0).getMarks().isEmpty()) {
product_addmore_spinner.setSelection(progresscard.indexOf(toppingtypelist.get(0).getMarks()));
}
}
}
You can set the spinner including the adapter, the default value in the onBindViewHolder of the recyclerview adapter. Also set the position as the tag of the spinner in the adapter like: vh.view.setTag(position);
Now implement the OnItemSelectedListener in the activity or the fragment and pass it onto the recyclerview adapter. Since you have already set the position of the spinner as the tag, you can easily extract the index of the progress object in the ArrayList.
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int index = (int) parent.getTag();
parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};

Update checkbox in CheckedTextView which is inside a ListView

I am a noob android studio and this is my first app I am developing.
Context: I have a ListView lv which is populated with CheckedTextViews using a ListAdapter.
ListAdapter adapter = new SimpleAdapter(
c, manageTrackers.trackers,
R.layout.list_item, new String[]{"id", "mobile", "status"},
new int[]{R.id.trackerID, R.id.trackerMobile, R.id.trackerStatus});
lv.setAdapter(adapter);
I have set up the OnItemClickListener for lv as shown below which checks and unchecks the check boxes as expected. I want the checks to remain persistent when I navigate between activities, so I am storing a key in the selectedTrackers array list.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.trackerID);
HashMap s = (HashMap)lv.getItemAtPosition(i);
String mob = (String)s.get("mobile");
//checked and pressed
if (ctv.isChecked())
{
ctv.setChecked(false);
for (int j = 0; j < selectedTrackers.size(); j++)
{
if (selectedTrackers.get(j) == mob)
{
selectedTrackers.remove(j);
break;
}
}
}
//not checked
else
{
ctv.setChecked(true);
selectedTrackers.add(mob);
}
}
});
When I navigate back to the activity with the list view, I call a function getSelectedTrackers which I want to select the saved checkboxes based on the key in selectedTrackers
public static void getSelectedTrackers()
{
if (basicSettings.selectedTrackers.size() == 0) return;
for (int i = 0; i < trackers.size(); i++)
{
HashMap s = trackers.get(i);
String mob = (String)s.get("mobile");
for (int j = 0; j < basicSettings.selectedTrackers.size(); j++)
{
if (basicSettings.selectedTrackers.get(j).equals(mob))
{
View v = getViewByPosition(i, lv);
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.trackerID);
ctv.setChecked(true);
//******************************
//some call to update the view HERE
//******************************
break;
}
}
}
}
Question: I have confirmed that the function finds the correct checkbox, but none of the check boxes are displayed as being selected after calling setChecked(). I have scoured SO and tried invalidating, refreshing drawable state, notifyDataSetChanged, and I can't seem to figure it out how to get it to work. What's the best way to do this? Any help is appreciated!

ListView getcount row and display in TextView

In my home activity. I have listview with id list and textview with id count.
Here's the code:
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int count = 0;
for (int i = 0; i <= list.getLastVisiblePosition(); i++) {
if (list.getChildAt(i) != null) {
count++;
counter.setText(count + "");
}
}
I want to display in textview of rows in listview
Do you want to display how many items is in ListView or visible on screen?
For first option:
If you use ListView, then you have to use some ListAdapter (for example descendant of BaseAdapter or ArrayAdapter) which has method
getCount()
This returns, how many items is in adapter and also in ListView.
edit:
TextView countTextView; // here you want to set number of items
ListView lv; // your ListView
BaseAdapter adapter; // your adapter, that is used with ListView
// call this method in some listener
private void showNumberOfItems() {
int count = adapter.getCount();
countTextView.setText(String.valueOf(count));
}
You can use getLastVisiblePosition() method to count the number of rows,
int count=0;
for(int i = 0; i <= list.getLastVisiblePosition(); i++)
{
if(list.getChildAt(i)!= null)
{
count++; // saying that view that counts is the one that is not null, because sometimes you have partially visible items....
}
}
and then set the Text,
counter.setText(count + "");
Edit-
try something like this,
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int count = 0;
for (int i = 0; i <= list.getLastVisiblePosition(); i++) {
if (list.getChildAt(i) != null) {
count++;
}
}
counter.setText(count + "");

Swapping two rows in ArrayAdapter

I've created a ListView that in each row has a button with UP and DOWN arrow. Pressing these buttons makes the row to be shifted one position up or down.
I've achieved it by implementing OnClickListener for both buttons in a the override method getView. It works as it should however I fill bad with that cuz it seems to be highly memory consuming and lots of code is doubled.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = inflater.inflate(R.layout.row_layout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
CheckBox checkBox = (CheckBox) rowView.findViewById(R.id.checkbox);
checkBoxes.add(position, checkBox);
String address = this.getItem(position).getAddress();
String tokenizedAddress = tokenizeAddress(address);
textView.setText(tokenizedAddress);
ImageButton buttonUp = (ImageButton)rowView.findViewById(R.id.button_up);
ImageButton buttonDown = (ImageButton)rowView.findViewById(R.id.button_down);
buttonUp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ListAdapter adapter = ListAdapter.this;
if(position != 0 ){
GameTask current = adapter.getItem(position);
ArrayList<GameTask> list = new ArrayList<GameTask>();
for( int i = 0; i < adapter.getCount(); i++ )
list.add(adapter.getItem(i));
list.remove(position);
list.add(position-1, current);
adapter.clear();
for( int i = 0; i < list.size(); i++ ){
adapter.add(list.get(i));
}
adapter.notifyDataSetChanged();
}
}
});
buttonDown.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ListAdapter adapter = ListAdapter.this;
if(position != adapter.getCount()-1 ){
GameTask current = adapter.getItem(position);
ArrayList<GameTask> list = new ArrayList<GameTask>();
for( int i = 0; i < adapter.getCount(); i++ )
list.add(adapter.getItem(i));
list.remove(position);
list.add(position+1, current);
adapter.clear();
for( int i = 0; i < list.size(); i++ ){
adapter.add(list.get(i));
}
adapter.notifyDataSetChanged();
}
}
});
return rowView;
}
Both listeners do almost the same, the only difference is the condition and the value of shifting +1/-1. I was wondering about creating the inner class implementing OnClickListener in the extended ArrayAdapter class however, I have no idea, how I could then pass the position of the row clicked to this inner class.
Instead of adding and removing elements from your ArrayList, you can better implement Collections.swap(List list, int firstElementIndex, int secondElementIndex) it would be much easier as you don't have to iterate through the whole Collection. A simple example for the same can be found here.
You could make a method that would be used by both buttonUp and buttonDown. This method could take as a parameter the type of action that was pressed (UP/DOWN), and the position of item in ListView, and then call this method in both of your click listener passing the appropriate action.
Example:
// 2 new constants
private static final int UP = 0;
private static final int DOWN = 1;
// Based on "type", increment or decrement the position.
private void changeRow(int type, int position){
if(type==UP){
position=position-1;
}else if(type==DOWN){
position=position+1;
}
// ........
// Then in your "for" cicle you specify:
list.add(position, current);
// ........
}
Then in the onClick() method of buttonUp you specify:
changeRow(UP, position);
and for buttonDown:
changeRow(DOWN, position);
This can be easily achieved
The way to do this is to store the data to be displayed in an List
Then when the user clicks the up or down arrow
Swap the references of data items which are shifting position using Collections.swap(List, int, int)
Then call notifyDataSetChanged on the adapter

ListView item setTextColor modified other elements

I have a ListView backed by SimpleCursorAdapter and custom ViewBinder. I want to make items in this listview change their color on clicking. If I do that in the OnClickListener - it works paritally, changing the color of the item clicked, and of the items down the list, each 7th (I guess, the period depends on on the viewable area of the listview).
Can anyone suggest how to deal with this? Or, maybe point to a more elegant way of making items in the listView selectable?
Thank you.
UPD: (sorry for bad formatting - this is the first time I post a question):
Below is how I try to make an item in the ListView "selected":
private void setupListView(final ListView lv) {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, final long id) {
RelativeLayout layout = (RelativeLayout) view;
int color;
if (conditionMet) {
color = R.color.gray;
} else {
color = R.color.red;
}
for(int i = 0; i < layout.getChildCount(); i++) {
((TextView)layout.getChildAt(i)).setTextColor(getResources().getColor(color));
}
return;
}}
This is how I init the adapter:
final SimpleCursorAdapter adapter =
new SimpleCursorAdapter(
this,
itemId,
cursor,
from,
to
);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
final TextView textView = (TextView) view;
// do necessary conversions
return true;
}
});
listView.setAdapter(adapter);
You can use the property android:listSelector to set the theme or any drawable or color of the currently selected item in a list.
Since no other answer, and, I think, I had some troubles with the suggestion below, I post how I did it:
I store ids of the items clicked in a special map
in the listview onclick I check whether the id of the just clicked item is in the map: if yes, I remove it and make the item and its children color A, otherwise I add the id to the map and set the color to B
public void onItemClick(AdapterView<?> adapterView, View view, int position, final long id) {
Context ctx = MainActivity.this;
RelativeLayout layout = (RelativeLayout) view;
try {
int color;
if (items.containsKey(id)) {
items.remove(id);
color = R.color.gray;
tempIds.remove(id);
} else {
items.put(id, sum);
color = R.color.red;
tempIds.add(id);
}
for (int i = 0; i < layout.getChildCount(); i++) {
final TextView textView = (TextView) layout.getChildAt(i);
textView.setTextColor(getResources().getColor(color));
}
} catch (ParseException e) {
Log.e(MainActivity.class.toString(), "Exception parsing", e);
}
return;
}
}

Categories

Resources