I have an android application that shows a grid view that shows:
1
2
3
4
GridView gridview=(GridView)findViewById(R.id.GridView_test);
DataBaseHelper dbhelper=new DataBaseHelper(this);
ArrayList<String> test=new ArrayList<String>(5);
backlinksadapter.add("1");
backlinksadapter.add("2");
backlinksadapter.add("3");
backlinksadapter.add("4");
ArrayAdapter mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test);
gridview.setAdapter(mAdapter);
By the moment is working, but i would like to show foreach line of the grid, 2 columns with the values of a 2 dimensional array (something like the GridView in ASP.Net - as datasource -).
I would like to show:
1 | Person 1
2 | Person 2
3 | Person 3
4 | Person 4
Any idea?
Does it have to be a grid view? Will a ListView work?
I wrote a ListView and ListActivity that displays two items in each row. I started with the SDK supplied simple_list_item_2.xml layout that lists two items per row but places one on top of the other (two lines) with the second line using a smaller font. What I wanted was both items on the same line, one to the right and one to the left.
First I copied the simple_list_item_2.xml into my project's res/layout directory under a new name and changed the property android:mode="twoLine" to "oneLine" while still keeping the view element name as "TwoLineListItem". I then replaced the two inner elements with ones that did what I wanted.
In the code to initialize the list, I created a MatrixCursor and filled it with the desired data. To support two items, each row in the MatrixCursor requires three columns, one being a primary key, "_id", and the other two columns being the items that I wanted to be displayed. I was then able to use a SimpleCursorAdapter to fill in and control the ListView.
My Layout XML File:
<?xml version="1.0" encoding="utf-8"?>
<TwoLineListItem
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="2dip"
android:paddingBottom="2dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:mode="oneLine"
>
<TextView
android:id="#android:id/text1"
android:gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
android:id="#android:id/text2"
android:gravity="right"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:layout_marginRight="6dip"
android:layout_toRightOf="#android:id/text1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/MainFontColor"
/>
</TwoLineListItem>
Note that I used "left" and "right" android:gravity values to make the left side item left justified and the right side item right justified. You will need different gravity values for your layout plus you will need properties to control the size of the left side item that I did not need.
The method in my ListActivity class that initialized the ListView:
private void initListView()
{
final String AuthorName = "Author: ";
final String CopyrightName = "CopyRight: ";
final String PriceName = "Price: ";
final String[] matrix = { "_id", "name", "value" };
final String[] columns = { "name", "value" };
final int[] layouts = { android.R.id.text1, android.R.id.text2 };
MatrixCursor cursor = new MatrixCursor(matrix);
DecimalFormat formatter = new DecimalFormat("##,##0.00");
cursor.addRow(new Object[] { key++, AuthorName, mAuthor });
cursor.addRow(new Object[] { key++, CopyrightName, mCopyright });
cursor.addRow(new Object[] { key++, PriceName,
"$" + formatter.format(mPrice) });
SimpleCursorAdapter data =
new SimpleCursorAdapter(this,
R.layout.viewlist_two_items,
cursor,
columns,
layouts);
setListAdapter( data );
} // end of initListView()
The parameter to the MatrixCursor constructor is an array of strings that define the order and the names of the columns in the cursor. Important: Make sure to add an "_id" column, without it the MatrixColumn will throw an exception and fail to work!
The three variables, mAuthor, mCopyright and mPrice, are three data members in my ListAdaptor class and they are initialized elsewhere. In my actual code, mAuthor is actually built in this method from a list of author names. The author names are concatenated into a single string using "\n" as separators between the names. This causes the multiple author names to appear on different lines in the same TextView.
The SimpleCursorAdapter ctor parameters are the ID of the View to use for each List row, the cursor containing the data, an array of strings where each element is the name of the column from the cursor (in the order to get them) and a corresponding array of View IDs for the View to use for each item in the List row.
If you can't find an existing adapter that has those properties, you can create your own custom adapter and have it map to your view.
The Hello, GridView tutorial shows how to do this.
JRL is right, you should write your own custom adapter which will let you control what will be displayed in each row. You might find this helpful. A more advanced example can be found here http://developerlife.com/tutorials/?p=327.
If you don't want/have to use a list a TableLayout could display your data as well. But that would be the manual approach since you'd have to fill each cell.
Best of success.
Why not create a class, whose toString() returns str(id) + " | " + personName, and use it as a template class instead of the String object?
You can simply add this in your XML
android:numColumns="2"
Related
I use AutoCompleteTextView in my project.
XML:
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textfield"
android:hint="Search..."/>
Kotlin:
val autocompleteOptions = ["France Paris", "UK London", "UK York", "Sydney Australia", "Vien Austria", "Tokyo Japan", "Kiev Ukrain", "Tallinn Estonia"]
// Initialize a new array adapter object
val arrayAdapter = context?.let {
ArrayAdapter<String>(
it, // Context
android.R.layout.simple_list_item_1,
autocompleteOptions // Array
)
}
// Set the AutoCompleteTextView adapter
autoCompleteTextView.setAdapter(arrayAdapter)
The problem here is that when I add white space in the autocomplete text field during the search the dropdown disappears.
It looks like the search does not recognize the white space character as part of the searched string.
For example, if I start to print in autocomplete text field "UK" I will get two options in autocomplete dropdown "UK London" and "UK York",
when I continue to print and add white space the autocomplete dropdown disappears.
I question how to prevent the disappearance of autocomplete dropdown when white space is added during the search.
I have an Alert Dialog which consists of a ListView. In that list the first option is "Create WatchList". The remaining options in that list are all the other available Watchlist in the app. What I want is :
To Bolden the "Create Watchlist"
Change the Colour of "Create WatchList"
I have already tried 4 methods of achieving this but none of them worked. I put all of my methods in bullet form.
Storing and formatting "Create WatchList" in strings.xml and calling it from the adapter but it still doesn't work
<string name="create_watchlist"><b>Create Watchlist</b></string>
In Java
String createWatchList = context.getResources().getString(R.string.create_watchlist);
Then I add it to the List
alertList.add(0,createWatchList);
With this above method the text appears with no formatting.
Then I using fromHtml function but still I got the same results
CharSequence styledString = Html.fromHtml(createWatchList );
Then I add it to the list
alertList.add(0,styledString.toString());
Then I tried this in a text view but it seems that ListViews cannot accept
TextViews.
The Latest I have tried is this:
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
int start = 0;
spannableStringBuilder.append(createWatchlist);
spannableStringBuilder.setSpan(new ForegroundColorSpan(0xFFCC5500),start,start+createWatchlist.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD),start,start+createWatchlist.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
alertList.add(0,spannableStringBuilder.toString());
I have tried this new method:
TextView textView = new TextView(context);
textView.setText(createWatchlist);
textView.setTypeface(textView.getTypeface(),Typeface.BOLD);
textView.setTextColor(context.getResources().getColor(R.color.lightRed));
alertList.add(0,textView);
After trying this new above method I get a message "Wrong 2nd argument type. Found: 'android.widget.TextView', required: 'java.lang.String'"
None of the above methods worked for me. Anyone out there who has any solutions to this please help!!!
You can set the style and color for the TextView inside the adapter. Just check if it is the first item and do whatever you want with the TextView.
For making it bold:
textView.setTypeface(textView.getTypeface(), Typeface.BOLD)
And for setting a color:
textView.setTextColor(getResources().getColor(R.color.yourColor));
I have simple problem with my fragment.. So i have a spinner and array string contain tow values.. On other hand and i have values on my firebase, I want set text from firebase not set. when i do that the problem arises.. the spinner run without click on it and the array disappeared.
Note: i do that in activity and the problem does not occur and working 100%, i have this problem just in fragment.
// Array
String[] priv_secu_sec_values = new String[] {"All", "Friends"};
// Create adapter
final ArrayAdapter<String> myAdapter = new ArrayAdapter<String>
(getActivity(),
android.R.layout.simple_dropdown_item_1line,priv_secu_sec_values);
// Create Spinner
final MaterialBetterSpinner edit_priv_secu = (MaterialBetterSpinner)
v.findViewById(R.id.edit_sec_send);
edit_priv_secu.setAdapter(myAdapter);
// Get Value from firebase and set text
String priv_secu_send =
dataSnapshot.child("rece_sec").getValue().toString();
edit_priv_secu.setText(priv_secu_send);
// Spinner XML Code:
<com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner
android:id="#+id/edit_sec_send"
android:layout_width="115dp"
android:layout_height="63dp"
android:layout_gravity="center"
android:layout_marginTop="12dp"
android:padding="5dp"
android:hint="#string/Who"
android:textSize="14sp"
app:met_floatingLabel="normal" />
My problem when is set text from firebase:
enter image description here
when i remove code set text from firebase and the problem does not occur
enter image description here
what i want..
enter image description here
I have a TextView within a ScrollView, which currently scrolls to the bottom of the TextView.
The TextView is filled dynamically constantly updating (the TextView is essentially acting as an actions console).
However, the problem I am having is that when the dynamic text is added to the ScrollView, the user can scroll past the text into black space, which is increasing everytime more content is added to the TextView.
I have tried various different apporaches however none of these gave the right outcome. I cannot use maxLines or define height of the layouts as I need this to be dynamic for the various screen sizes, which the number of lines visible constantly changing.
I had also orginally done this progromatically, however this was crashing at random time and therefore would like to keep it in my layout (better usabilty), example code below:
final int scrollAmount = update.getLayout().getLineTop(update.getLineCount()) - update.getHeight();
if(scrollAmount > 0)
{
update.scrollTo(0, scrollAmount);
}
The code below is my current layout xml being used to automatically scroll my TextView to the bottom as content is added:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/spacer2"
android:layout_below="#+id/spacer1"
android:fillViewport="true" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/battle_details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="12dp"
android:layout_gravity="bottom" />
</LinearLayout>
</ScrollView>
EDIT - This is the code I am using to add text to my TextView:
private void CreateConsoleString()
{
TextView update = (TextView)findViewById(R.id.battle_details);
String ConsoleString = "";
// BattleConsole is an ArrayList<String>
for(int i = 0; i < BattleConsole.size(); i++)
{
ConsoleString += BattleConsole.get(i) + "\n";
}
update.setText(ConsoleString);
}
EDIT 2 - I add content to the BattleConsole like this:
BattleConsole.add("Some console text was added");
CreateConsoleString();
To sum up my only issue is the ScrollView and/or TextView is adding blank space to the bottom rather than stop the user from scrolling at the last line of text. Any help or guidence as to where I am going wrong would be much appreciated.
It looks like that when you call
BattleConsole.get(i)
it sometimes returns an empty String so you are just basically adding new lines to your TextView.
You can do this for example:
StringBuilder consoleString = new StringBuilder();
// I'm using a StringBuilder here to avoid creating a lot of `String` objects
for(String element : BattleConsole) {
// I'm assuming element is not null
if(!"".equals(element)) {
consoleString.append(element);
consoleString.append(System.getProperty("line.separator")); // I'm using a constant here.
}
}
update.setText(consoleString.toString());
If you could post the code of BattleConsole I could help you more.
As a footnote: it is encouraged to use camelCase in java. Only class names start with capital letters in java according to the convention.
Im trying to implement an activity that uses ExpandableListView and I have gotten so far but now I have found some strange behavior.
My activity is meant to record food intake as specified by the user. they have a choice of menus (breakfast, lunch and dinner - the outer group) which expand to show their contents.
when a user clicks on an inner menu item a dialog appears asking them for the qty. once they enter a qty and dismiss the dialog the text on the menu item changes to reflect the quantity of that item that has been consumed
The above image shows the list in a closed state.
below is the list after I have opened the lunch menu and clicked on 'Potato Chips' and indicating a Quantity of 1. As you can see the 'Potato' itemtext has now been changed to reflect the Qty of 1.
The strange part happens now. if I click on 'Lunch' and close the list and then click on it again re-opening it, the 'Qty X 1' text has jumped to another item (Milk)
each time I open and close the list it jumps back and forth between the two items. Also if I open up other items, such as breakfast, I find that they too have now gotten items with 'Qty X 1' even though I havent clicked them.
The bits of code that are relevant are as such:
The XML for a child element:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/childname"
android:paddingLeft="50dip"
android:textSize="14dip"
android:textStyle="italic"
android:layout_width="200dip"
android:textColor="#color/black"
android:layout_height="40dip"/>
<TextView android:id="#+id/qty_display"
android:text="-"
android:textSize="14dip"
android:textStyle="italic"
android:layout_width="50dip"
android:textColor="#color/black"
android:layout_height="wrap_content"/>
</LinearLayout>
The code thats triggered on clicking a child element:
public boolean onChildClick(
ExpandableListView parent,
View v,
int groupPosition,
int childPosition,
long id) {
// open the dialog and inflate the buttons
myDialog = new Dialog(this);
myDialog.setTitle("Food Item Qty");
myDialog.setContentView(R.layout.food_intake_dialog);
final Button ok = (Button)myDialog.findViewById(R.id.fi_ok_but);
Button cancel = (Button)myDialog.findViewById(R.id.fi_cancel_but);
//the id for this item is stored as a hash key in a map (say, item_id01)
String key = "item_id"+groupPosition+""+childPosition;
current_selected_food_item_id = Integer.parseInt(itemMap.get(key));
// inflate the textview that shows the qty for this item on the expandablelist
barQty = (TextView) v.findViewById(R.id.qty_display);
// set the ok button to record teh quantity on press
ok.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
//inflate the input box that receives quantity from user
EditText fiQty = (EditText) myDialog.findViewById(R.id.fiQty);
// get the quantity and append the text on hte list item
String qty = fiQty.getText().toString();
barQty.setText("Qty X "+qty);
//open the database and save state
FoodIntake.this.application.getFoodIntakeHelper().open();
FoodIntake.this.application.getFoodIntakeHelper().storeFoodIntakeLog(current_selected_food_item_id,qty,visit_id,remote_visit_id);
String log = FoodIntake.this.application.getFoodIntakeHelper().getFoodIntakeLog(visit_id);
FoodIntake.this.application.getFoodIntakeHelper().close();
// append the main food intake list and close the dialog
list.setText("Food Intake Log:\n\n"+log);
myDialog.cancel();
}
});
The above code opens a dialog, accepts a value for quantity, appends the list element to reflect this, also saves to database and sets a textview with the selected item and quantity.
Sorry to just dump a whole load of code, but this has me stumped and hopefully someone can help.
Thanks
Kevin
Android reuses dialogs. So the behavior you are seeing could be a result of that. You could use a activity managed dialog and use onPrepareDialog() to update dialog contents.
I don't think the problem is with the dialogs. I had the same problem in my project and couldn't fix it. I think the ExpandableListView has a bug when opening children. I had only one child per group and when I expand a group, the child moves to another group. After testing, I found out that when I expand the children are reloaded.