I have an AutoCompleteTextView inside a TextInputLayout (following the Material Design guidelines - https://m2.material.io/components/menus/android#exposed-dropdown-menus). I would like to have an icon in the left of every item of the list, and this icon would be different for every item.
main_layout.xml
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu" >
<AutoCompleteTextView
android:id="#+id/gender_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/gender"
android:inputType="none" />
</com.google.android.material.textfield.TextInputLayout>
list_item_gender.xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceSubtitle1" />
MainActivity.java
/**
* Define gender list for form completion
*/
private void defineLists() {
// Gender spinner
AutoCompleteTextView gender = findViewById(R.id.gender_list);
ArrayAdapter<String> gender_adapter = new ArrayAdapter<>(this, R.layout.list_item_gender, getGenderList());
gender.setAdapter(gender_adapter);
}
/**
* Get the gender list
* #return the gender list in ArrayList<String> object
*/
private ArrayList<String> getGenderList() {
ArrayList<String> genderList = new ArrayList<>();
genderList.add(getString(R.string.man));
genderList.add(getString(R.string.woman));
genderList.add(getString(R.string.unknown));
return genderList;
}
Thanks !
Related
I have a big SQLite database (7000+ items) with 16 columns per row. I would like to populate my custom recycler view, that I already made, with items from the database to make a huge recycler view list.
My question is this: How would you go about iterating through 2 entire columns of all of the rows. I need to fetch a name and an ID of each and every single item in the database and assign those values to 2 text views, that I created through a custom recycler view adapter. I already have a method in the database that returns a number of total rows (aka items) in a database. I would like to make a loop with i < getDbSize(); but I don't have a clear idea on how I would go about on incrementing through 2 particular columns of all rows and then applying that information onto a card in the recycler view.
Here is the xml code where recycler view sits:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".CollegeFragment"
android:background="#color/colorPrimaryDark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="College Search Tool"
android:textSize="28sp"
android:padding="10dp"
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/grad_bg"
android:paddingBottom="10dp"
android:paddingRight="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ipeds id:"
android:textSize="24sp"
android:padding="10dp"
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"/>
<EditText
android:id="#+id/et_ipeds"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:background="#drawable/et_alt1_bg"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name: "
android:textSize="24sp"
android:padding="10dp"
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"/>
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:background="#drawable/et_alt1_bg"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RESULT"
android:textSize="28sp"
android:padding="10dp"
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"/>
</LinearLayout>
</FrameLayout>
and Java:
public class CollegeFragment extends Fragment implements ItemClickListener{
private RecyclerView recyclerView;
private CustomRecyclerAdapter customRecyclerAdapter;
private List<CollegeItem> collegeItemList = new ArrayList<>();
private DatabaseCollege dbCollege;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myFragmentView = inflater.inflate(R.layout.fragment_college, container, false);
dbCollege = new DatabaseCollege(getActivity());
recyclerView = myFragmentView.findViewById(R.id.recycler);
customRecyclerAdapter = new CustomRecyclerAdapter(collegeItemList, getActivity());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(customRecyclerAdapter);
customRecyclerAdapter.setItemClickListener(this);
//populate collegeItemList with dummy values for testing
String name = "College 1";
String id = "12345647653";
String name2 = "College 2";
String id2 = "12345";
CollegeItem college = new CollegeItem(name, id);
CollegeItem college2 = new CollegeItem(name2, id2);
collegeItemList.add(college);
collegeItemList.add(college2);
return myFragmentView;
}
#Override
public void onClick(View v, int position) {
String name = collegeItemList.get(position).getName();
String id = collegeItemList.get(position).getId();
}
public void populateList() {
int numOfColleges = dbCollege.getNumOfColleges();
for(int i = 0; i < numOfColleges; i++) {
//read in data from database into collegeItemList recyclerView here
}
}
}
I also included a picture with what I am trying to achieve that contains manually inserted variables. I basically want to populate that list with cards that each contain info(ID and name) about each and every item from database.
You need to query the database first to get those two fields like below:
ArrayList<CollegeItem> arr = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
arr.add(new CollegeItem(cursor.getString(1),
cursor.getString(2));
cursor.moveToNext();
}
cursor.close();
db.close();
return arr;
Then pass this ArrayList(arr) to the list view using Adaptor and map the values of Pair class to the XML components.
I am developing an android app where a user will input text to an EditText, then it will be added to a ListView.
But once a button with onClick value "start" is clicked, it will display each item of the ListView in a TextView with id displayText, in the order of each item and it will loop(Repeat) once it is exhausted.
Here is my Code
Math.java
public class Math extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_math);
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
}
public void AddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
itemsAdapter.add(itemText);
etNewItem.setText("");
}
public void start(View v){
RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
lc.setVisibility(View.GONE);
RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
tc.setVisibility(View.VISIBLE);
}
}
activity_math.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"
tools:context=".Math">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvContainer"
android:visibility="gone">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="30sp"
android:id="#+id/displayText"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/contentContainer">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lvItems"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btnAddItem" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etNewItem"
android:layout_alignTop="#+id/btnAddItem"
android:hint="Enter a new item"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/btnAddItem"
android:layout_toStartOf="#+id/btnAddItem"
android:layout_alignParentBottom="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"
android:id="#+id/btnAddItem"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="AddItem"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/btnAddItem"
android:onClick="start"/>
</RelativeLayout>
Okay, i think the issue is that you haven't given the TextView any thing to display. you have to convert the arrayList to a String array and use setText to display the Value.
add this part to the "start" method
String ls =System.getProperty("line.separator");// i used this to seperate the array items
String joint = TextUtils.join(ls, lvitems);
result.setText(joint);
That should work
Setup
In my app I have a section that creates rows of data to be saved in a database. Each row is built from a textbox, number box then "set" into a listview for display. Later on the user can open a "plan" created before and review the data.
I created a listview, a custom layout for the display line and figured out how to add/display each new row. However, when I perform the open, I create a dialog to display the list for plans, user selects on and the rows should display. They do not. I trace through the code and I see the arraylist for the adapter being populated and I call the notifydatasetchanged, but the main listview remains empty.
I am not using a customer adapter class, but just the Simple adapter.
This is the beginning of the Activity. I am still learning android coding so I tend to use generic names as I learn.
public class TrackItEqMainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public int rowCount = 1;
private static final String eTAG = "Exception";
final Context context = this;
// global variables needed for processing the add gaits display
**private ListView lstGaits;
private ListAdapter adapter;
private ArrayList<HashMap<String, String>> mylist;**
// *****
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(eTAG, "onCreate Build");
setTitle(R.string.activityManagePlans);
setContentView(R.layout.activity_track_it_eq_build);
Toolbar mySecondaryToolbar = (Toolbar) findViewById(R.id.my_secondaryToolbar);
setSupportActionBar(mySecondaryToolbar);
setActivityBuildListeners();
// set the objects needed to handle the dynamic gaits list
ListView lstGaits = (ListView) findViewById(R.id.lstMyGaits);
mylist = new ArrayList<HashMap<String, String>>();
try {
adapter = new SimpleAdapter(this, mylist, R.layout.gaits_detail,
new String[] { "keyGait", "keyTime" }, new int[] {
R.id.txtdisplayGait, R.id.txtdisplayTime });
lstGaits.setAdapter(adapter);
} catch (Exception e) {
Log.i(eTAG, e.getMessage());
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
SO when a user taps a new button a set of controls appear allowing to select a gait and enter a time. They then tap on the set button and in the set onClick, I add the data to the internal array and display the custom layout on the screen.
private Button.OnClickListener onClick_btnSet = new OnClickListener() {
#Override
public void onClick(View v) {
Spinner spinner = (Spinner) findViewById(R.id.spinner_gaits);
TextView textGait = (TextView) spinner.getSelectedView();
String gtResult = textGait.getText().toString();
TextView txtTime = (TextView) findViewById(R.id.txtSelected);
String tmeResult = txtTime.getText().toString();
buildDisplayLine(true,gtResult,tmeResult);
txtTime.setText("");
spinner.requestFocus();
}
};
The function that builds the line and adds to the array is this:
private void buildDisplayLine(boolean isNew, String gait, String time) {
HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("keyGait",gait); // put the col data in
map2.put("keyTime", time); // put the col data in
mylist.add(map2);
if (isNew) {
((BaseAdapter) (adapter)).notifyDataSetChanged();
}
}
All that works although a strange side effect is that the list will not display if the number keypad is visible. When I clear it off the list appears.
Ifa use wants to look at or change a plan they tap the open button. IT display a dialog box that shows a list of plans. Tap on a plan and all the elements should display:
private final ThreadLocal<OnClickListener> onClick_btnOpen = new ThreadLocal<OnClickListener>() {
#Override
protected OnClickListener initialValue() {
return new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_track_it_eq_open_plan);
dialog.setTitle("Open Exercise Plan...");
Button diaCancelButton = (Button) dialog.findViewById(R.id.btnCancelOpen);
diaCancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
// get a list of files from the local app plans
final eqDatabaseService eqDB = new eqDatabaseService(context, 2);
ArrayList<HashMap<String,String>> allPlans = eqDB.getPlanList();
if (allPlans.isEmpty()) {
Toast toast = new Toast(context);
toast.setGravity(Gravity.TOP, 0, 0);
Toast.makeText(context, "No Files to open, Please create one!", Toast.LENGTH_LONG).show();
return;
}
ListView lvPlan = (ListView) dialog.findViewById(R.id.lvPlans);
try {
adapter = new SimpleAdapter(context, allPlans, R.layout.plans_columns,
new String[] { "keyName", "keyENum" }, new int[] {
R.id.txtPlanName, R.id.txtNumElements });
lvPlan.setAdapter(adapter);
} catch (Exception e) {
}
//********************************************************
lvPlan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView txtplan = (TextView) v.findViewById(R.id.txtPlanName);
String planName = txtplan.getText().toString();
List<eqSessions_dt> myPlan = eqDB.getCurrentPlan(planName);
clearGrid();
for (eqSessions_dt row : myPlan) {
buildDisplayLine(false, row.get_gait(),Integer.toString(row.get_time()));
}
((BaseAdapter)(adapter)).notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
};
}
};
I have played around with this, did look at other similar questions and answers, but didn't see anything that would explain why the notify would not work. I avoided doing a custom adapter, trying to keep this simple at first. What am I missing that stops the list from displaying. I see the arraylist being filled and all related objects are global to the activity. I'll keep playing around, but I hope otehr eyes see what I miss.
This is the activity xml`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
tools:context="com.newproject.jhull3341.trackiteq.TrackItEqMainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_secondaryToolbar"
android:layout_width="fill_parent"
android:layout_height="?attr/actionBarSize"
android:background="#236dc1"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/lyFileAction">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="92dp"
android:layout_height="match_parent"
android:text="New"
android:id="#+id/btnNew"
android:layout_row="0"
android:layout_column="0"
android:layout_gravity="center_horizontal" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="92dp"
android:layout_height="match_parent"
android:text="Open"
android:id="#+id/btnOpen"
android:layout_row="0"
android:layout_column="1"
android:layout_gravity="center_horizontal" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="92dp"
android:layout_height="match_parent"
android:text="Save"
android:id="#+id/btnSave"
android:layout_row="0"
android:layout_column="2"
android:layout_gravity="center_horizontal" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="92dp"
android:layout_height="match_parent"
android:text="Delete"
android:id="#+id/btnDelete"
android:layout_row="0"
android:layout_column="3"
android:layout_gravity="center_horizontal" />
</GridLayout>
<GridLayout
android:layout_width="367dp"
android:layout_height="wrap_content"
android:id="#+id/grdEntry">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/label_time"
android:id="#+id/lblTime"
android:layout_row="0"
android:layout_column="1"
android:layout_marginBottom="5dp" />
<Spinner
android:layout_width="147dp"
android:layout_height="wrap_content"
android:id="#+id/spinner_gaits"
android:layout_row="1"
android:layout_column="0"
android:focusable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/label_Gait"
android:id="#+id/lblGait"
android:layout_row="0"
android:layout_column="0"
android:layout_marginBottom="5dp" />
<EditText
android:layout_width="124dp"
android:layout_height="wrap_content"
android:id="#+id/txtSelected"
android:layout_row="1"
android:layout_column="1"
android:layout_gravity="fill_horizontal|center_vertical"
android:singleLine="true"
android:numeric="integer" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="92dp"
android:layout_height="fill_parent"
android:text="Set"
android:id="#+id/btnSet"
android:layout_row="1"
android:layout_column="2"
android:layout_gravity="center_vertical"
android:clickable="true" />
</GridLayout>
<ListView
android:id="#+id/lstMyGaits"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/grdEntry" />
</LinearLayout>
this is the custom layout for each display row.`
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtdisplayGait"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="TextView"
android:textSize="18sp" />
<TextView
android:id="#+id/txtdisplayTime"
android:layout_width="80dp"
android:layout_height="44dp"
android:gravity="center_vertical"
android:text="TextView"
android:textSize="18sp" />
<ImageButton
android:id="#+id/btnRemoveLine"
android:layout_width="25dp"
android:layout_height="44dp"
android:layout_weight="0.39"
android:background="#color/wallet_bright_foreground_holo_dark"
android:elevation="1dp"
android:src="#android:drawable/btn_dialog" />
</LinearLayout>`
So this is my first app not following a tutorial. I have got the xml all laid out, spinner drop downs working also the first calculation working which is done by EditText numbers.
I am now wanting to use this first calculated answer along with one of the spinner selected values to do the next calculation
Here is my xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<EditText
android:id="#+id/inside"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:ems="10"
android:inputType="number"
android:gravity="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Inside Ø \n(mm)"
android:textSize="16dp" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:background="#android:color/darker_gray" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<EditText
android:id="#+id/outside"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:ems="10"
android:inputType="number"
android:gravity="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Outside Ø \n(mm)"
android:textSize="16dp" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:background="#android:color/darker_gray" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<EditText
android:id="#+id/coils"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:ems="10"
android:inputType="number"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Number of Coils"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<Spinner
android:id="#+id/thickness"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_weight="1"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
<Spinner
android:id="#+id/width"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_weight="1"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
</LinearLayout>
<Button
android:id="#+id/bt_calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="calculate"
android:text="Calculate" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="24dp">
<TextView
android:id="#+id/result_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="24dp">
<TextView
android:id="#+id/result_kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp">
<TextView
android:id="#+id/result_m2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<Button
android:id="#+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:layout_gravity="center_horizontal"
android:onClick="clear"
android:text="Clear" />
And here is the code
package com.example.android.engineerstoolbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import static com.example.android.engineerstoolbox.R.id.result_kg;
import static com.example.android.engineerstoolbox.R.id.result_m;
import static com.example.android.engineerstoolbox.R.id.result_m2;
public class CoilCalculator extends AppCompatActivity {
private EditText editText1;
private EditText editText2;
private EditText editText3;
private Spinner spinner1;
private Spinner spinner2;
private TextView resultM;
private TextView resultKG;
private TextView resultM2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coil_calculator);
//set spinner1 for user input of available thickness
Spinner dropdown = (Spinner) findViewById(R.id.thickness);
String[] items = new String[]{"Thickness", "1.2", "1.5", "2", "2.5", "3", "4"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
//set spinner2 for user input of available width
dropdown = (Spinner) findViewById(R.id.width);
items = new String[]{"Width", "1219", "1500", "1524"};
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
editText1 = (EditText) findViewById(R.id.inside);
editText2 = (EditText) findViewById(R.id.outside);
editText3 = (EditText) findViewById(R.id.coils);
resultM = (TextView) findViewById(result_m);
resultKG = (TextView) findViewById(result_kg);
resultM2 = (TextView) findViewById(result_m2);
//Set button to do calculations
Button bt_calculate = (Button) findViewById(R.id.bt_calculate);
bt_calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeCalculations();
}
});
//Set reset button to reset inputs
Button mButtonReset = (Button) findViewById(R.id.clear);
mButtonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText1.setText("");
editText2.setText("");
editText3.setText("");
resultM.setText("");
}
});
}
private void makeCalculations() {
double n1 = Double.valueOf(editText1.getText().toString());
double n2 = Double.valueOf(editText2.getText().toString());
double n3 = Double.valueOf(editText3.getText().toString());
//do the Lineal meter calculation
Double calculatedValue = ((((n1 + n2) / 2) * 3.141592654) * n3) / 1000;
double output = (double) Math.round(calculatedValue * 1000) / 1000;
//set the value to the textview, to display on screen.
resultM.setText(output + " Lineal Meters");
}
}
I know i need to set a listener of some sort to pick up the spinner value; but i am unsure where and so far i have not found a question on here that explains where to put the code.
The next calculation would look something like this
Double calculatedValue2 = output * (value of spinner2/1000);
//set the value to the textview, to display on screen.
resultM2.setText(calculatedValue2 + " M²");
I am pretty sure the double is not the way to go but wanted to show something for the next calculation
You have not actually assigned spinner1 and spinner2 to your Spinner objects.
//set spinner1 for user input of available thickness
spinner1 = (Spinner) findViewById(R.id.thickness);
String[] items = new String[]{"Thickness", "1.2", "1.5", "2", "2.5", "3", "4"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
spinner1.setAdapter(adapter);
//set spinner2 for user input of available width
spinner2 = (Spinner) findViewById(R.id.width);
items = new String[]{"Width", "1219", "1500", "1524"};
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
spinner2.setAdapter(adapter);
Then when you want to perform the calculation,
String selectedItem = spinner2.getSelectedItem().toString();
double selectedValue = Double.parseDouble(selectedItem);
Double calculatedValue2 = output * (selectedValue/1000);
//set the value to the textview, to display on screen.
resultM2.setText(calculatedValue2 + " M²");
If you want to call a listener when you are selecting a value from the spinner, you should use Spinner.setOnItemSelectedListener method. You can see this post for further information.
setOnItemSelectedListener of Spinner does not call
You just had to overwrite the onItemSelected method.
Making a simple program which will generate a multiple choice form. I have an sing_select.xml which acts as the template for making each question. Then, in code I wanted to populate my main.xml with a bunch of these templates customized. Though it works great for the first question, any subsequent questions do not get displayed. Not sure what I'm doing wrong. I know there isn't an overlap as I manually hid the first question.
Java File
public class FormFillerActivity extends Activity
{
private LinearLayout mQuestionList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Must come before setContentView or program crashes
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Must set before accessing layout elements or program crashes
setContentView(R.layout.main);
mQuestionList = (LinearLayout) findViewById(R.id.Body_Layout);
initForm();
}
private void initForm()
{
int count = 1;
ArrayList<String> answers = new ArrayList<String>();
answers.add("Single");
answers.add("Married");
answers.add("Separated");
answers.add("Divorced");
mQuestionList.addView(addSingSelectQuestion(count++, "What is your marital status?", answers));
answers.clear();
answers.add("Male");
answers.add("Female");
mQuestionList.addView(addSingSelectQuestion(count++, "What is your gender?", answers));
}
private View addSingSelectQuestion(int count, String question, ArrayList<String> answers)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View container = inflater.inflate(R.layout.sing_select, null);
((TextView) container.findViewById(R.id.Sing_Select_Num)).setText(count + ") ");
((TextView) container.findViewById(R.id.Sing_Select_Text)).setText(question);
RadioGroup rg = (RadioGroup) container.findViewById(R.id.Sing_Select_Answer);
//Generate radio group answers
Iterator<String> it = answers.iterator();
while (it.hasNext())
{
RadioButton rb = new RadioButton(rg.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
String ans = it.next();
rb.setId(answers.indexOf(ans));
rb.setLayoutParams(params);
rb.setText(ans);
rb.setTextColor(getResources().getColor(R.color.black));
rb.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.txt_normal));
rg.addView(rb);
}
return container;
}
}
main.xml (stripped out unrelated UI elements)
<?xml version="1.0" encoding="utf-8"?>
...
<ScrollView
android:id="#+id/Body_Scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/Footer"
android:layout_below="#id/Title"
android:scrollbars="vertical" >
<LinearLayout
android:id="#+id/Body_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/marg_normal"
android:padding="#dimen/pad_large" >
</LinearLayout>
</ScrollView>
...
sing_select.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Sing_Select_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:padding="8dp" >
<TextView
android:id="#+id/Sing_Select_Num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#) "
android:textColor="#color/black"
android:textSize="#dimen/txt_normal" />
<TextView
android:id="#+id/Sing_Select_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Sing_Select_Num"
android:layout_toRightOf="#+id/Sing_Select_Num"
android:text="The Question?"
android:textColor="#color/black"
android:textSize="#dimen/txt_normal" />
<RadioGroup
android:id="#+id/Sing_Select_Answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Sing_Select_Text"
android:layout_below="#+id/Sing_Select_Text"
android:layout_toLeftOf="#+id/Sing_Select_Trans_Button" >
</RadioGroup>
<Button
android:id="#+id/Sing_Select_Trans_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_big"
android:padding="8dp"
android:text="Accept"
android:textSize="#dimen/txt_button" />
</RelativeLayout>
Try to set orientation to vertical for the *Body_Layout* LinearLayout. I think your pushing out of the screen the next rows after the first one(the width for the inflated view is set to fill the parent).