ListView elements are not displaying even though I've used almost identical code before. Sorry that I have to ask this type of question, but I seriously just don't understand why it's not working. None of the other similar questions I looked at were useful.
The heights of the items and ListView should be fine. Not sure what's going on. Thanks guys.
Here's the code dump:
Main Acitivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_city);
findViewById(R.id.loadingPanel).setVisibility(View.GONE); // remove loading animation
ArrayList<String> citiesList = new ArrayList<>();
citiesList.add("Waterloo");
citiesList.add("Guelph");
populateCities(citiesList);
}
public void populateCities(ArrayList<String> citiesList) {
// see what the list is
Toast.makeText(getApplicationContext(),citiesList.toString(),Toast.LENGTH_LONG).show();
// populate the ListView
CitiesListAdapter citiesListAdapter = new CitiesListAdapter(this, citiesList);
ListView citiesListView = (ListView)findViewById(R.id.cities_list);
citiesListView.setAdapter(citiesListAdapter);
// listen for when a city in the list is clicked
citiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// go to the bar list activity (send the city and province with it)
TextView lblCity = (TextView)view.findViewById(R.id.lblCity);
String city = lblCity.getText().toString();
Toast.makeText(getApplicationContext(), city, Toast.LENGTH_LONG).show();
}
});
}
Here's the list adapter code (CitiesListAdapter):
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CitiesListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> cities;
public CitiesListAdapter(Activity context, ArrayList<String> cities) {
super(context, R.layout.cityitem);
this.context = context;
this.cities = cities;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.cityitem, null, true);
TextView lblCity = (TextView)rowView.findViewById(R.id.lblCity);
lblCity.setText(this.cities.get(position));
return rowView;
}
}
Then here's the main layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.myapp.SelectCity">
<RelativeLayout
android:id="#+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:id="#+id/progressBar" />
</RelativeLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnBack"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:onClick="back"
android:src="#mipmap/ic_menu_back"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnRefresh"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:onClick="refresh"
android:src="#mipmap/ic_action_refresh"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Select City"
android:id="#+id/lblTitle"
android:layout_below="#+id/btnBack"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/listViewLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/lblTitle"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp">
<ListView
android:background="#F00"
android:id="#+id/cities_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/listViewLayout"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Then the ListView item layout (cityitem.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="City"
android:id="#+id/lblCity" />
</LinearLayout>
Edit: Looks like I'm also getting this stupid error that Android can't seem to fix (just sneaks in the LogCat):
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7ccc40
Not sure if that's why nothing is displaying.
Screenshot: http://prntscr.com/avpy9s
The super call in your constructor doesn't include the ArrayList, nor are you overriding getCount() to return the list size, so your Adapter is returning 0 for the item count, and the ListView won't try to retrieve any Views. You could include the ArrayList in the super call, or override the getCount() method to return cities.size().
However, you don't necessarily need a custom Adapter for a simple ArrayList of Strings. You could simply use the constructor for ArrayAdapter that takes a layout and a TextView resource ID.
ArrayAdapter<String> citiesListAdapter = new ArrayAdapter<>(this,
R.layout.cityitem,
R.id.lblCity,
cities);
There's no layout in the ListView. You need to add layout(Linear or Relative) inside the ListView. Like this!
<ListView
<RelativeLayout />
/>
In the layout, you declare what you wanna show - TextView or ImageView or etc.
Related
I'm currently doing a project that requires me to continuously display data from a Bluetooth device, in this case, the weight measurements from four different sensors.
I have tried creating a List View using a custom adapter but it would only display the set of inputs once. The data shown on the List View would only update if I exit and re-enter the fragment.
I have been trying to find a way to continuously add in a new set of inputs onto the List View while retaining the previous data on top but I can't seem to find a good reference for it.
This is an example of what my List View looks like:
My Code:
My CustomAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue1;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue2;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue3;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue4;
public class Adapter_inputs extends ArrayAdapter<Model_inputs> {
private final int resourceLayout;
public Adapter_inputs(Context context, int resourceLayout, List<Model_inputs> inputsList) {
super(context, resourceLayout, inputsList);
this.resourceLayout = resourceLayout;
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v == null){
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
v = layoutInflater.inflate(resourceLayout, null);
}
Model_inputs inputs = getItem(position);
if(inputs != null){
TextView input1TV = (TextView) v.findViewById(R.id.InputValue1);
TextView input2TV = (TextView) v.findViewById(R.id.InputValue2);
TextView input3TV = (TextView) v.findViewById(R.id.InputValue3);
TextView input4TV = (TextView) v.findViewById(R.id.InputValue4);
if(input1TV != null){
input1TV.setText("Input Value 1:" + InputValue1);
}
if(input2TV != null){
input2TV.setText("Input Value 2:" + InputValue2);
}
if(input3TV != null){
input3TV.setText("Input Value 3:" + InputValue3);
}
if(input4TV != null){
input4TV.setText("Input Value 4:" + InputValue4);
}
}
return v;
}
}
My Model
package com.shoeinsoleweight.bluetooth_java_fragment;
public class Model_inputs{
String Input1;
String Input2;
String Input3;
String Input4;
public Model_inputs(String Input1, String Input2, String Input3, String Input4){
this.Input1 = Input1;
this.Input2 = Input2;
this.Input3 = Input3;
this.Input4 = Input4;
}
public String getInput1() {
return Input1;
}
public String getInput2() {
return Input2;
}
public String getInput3() {
return Input3;
}
public String getInput4() {
return Input4;
}
}
My Fragment
public class history_fragment extends Fragment {
private View decorView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.history_fragment, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Model_inputs> inputsList = new ArrayList<>();
Model_inputs inputs = new Model_inputs("a", "b", "c", "d");
inputsList.add(inputs);
ListView listView = (ListView) view.findViewById(R.id.InputValue_LV);
Adapter_inputs adapter_inputs = new Adapter_inputs(requireActivity(), R.layout.row_inputs, inputsList);
listView.setAdapter(adapter_inputs);
}
}
XML file for each set of data
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#BFFFFFFF"
android:backgroundTint="#2B2B2B"
android:orientation="vertical">
<TextView
android:id="#+id/InputValue1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 1:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/InputValue2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 2:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/InputValue3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 3:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/InputValue4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 4:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
XML file for fragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/nightsky"
tools:context=".history_fragment">
<FrameLayout
android:id="#+id/fl_navBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_nav">
<TextView
android:id="#+id/History_Text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:background="#null"
android:ems="10"
android:fontFamily="casual"
android:text="#string/history"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/InputValue_LV"
android:layout_width="match_parent"
android:layout_height="585dp"
android:layout_marginTop="80dp"
android:background="#BFFFFFFF"
android:backgroundTint="#2B2B2B" />
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#00019184"
app:itemIconTint="#FFFFFF"
app:itemTextColor="#FFFFFF"
app:menu="#menu/nav_menu" />
</RelativeLayout>
Instead of using List user ArrayList in the adapter. Then, when the bluetooth sends the data (this will be a listener which will be capturing the bluetooth data, probably a service or something similar), add the data set to the array list that you are passing to the Adapter and call the onDataSetChanged() function on adapter which is a built-in method to notify the adapter that dataset has been changed. like
list.add(new Model_inputs("a", "b", "c", "d"));
adapter.notifyDataSetChanged();
Here, "new Model_inputs("a", "b", "c", "d")" will be the new data set sent by the bluetooth device.
I would recommend to use RecyclerView instead of ListView, which provides a better way of inflating the views. i.e. it recycles the views upon scrolling.
I want to make an app that shows a list of books that relate to a given keyword. I made the ListView, EditText view and a search button. The layout is given below:
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<EditText
android:id="#+id/search_query_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="#string/hint" />
<Button
android:id="#+id/search_button1"
android:layout_width="42dp"
android:layout_height="42dp"
android:drawableLeft="#drawable/search"
/>
</LinearLayout>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Results" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible" />
</RelativeLayout>
</LinearLayout>
The XML for a single item in the list is given below.
list_layout.xml
<?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="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/list_item_height"
android:layout_margin="5dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/list_item_height">
<ImageView
android:id="#+id/thumbnail_imageview"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/kite_runner" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="#dimen/list_item_height"
android:layout_margin="5dp">
<TextView
android:id="#+id/title_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="The Kite Runner"
android:textColor="#000000"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/author_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/title_textview"
android:layout_marginBottom="10dp"
android:text="Khaled Hosseini"
android:textColor="#000000"
android:textSize="17sp" />
<TextView
android:id="#+id/publisher_texview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/author_textview"
android:text="Penguin Books"
android:textColor="#000000"
android:textSize="15sp" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I am using the Google Books API query to access the book list.
I have the base URL and I now need to add the value in the EditText view to this URL.
The custom adapter for the list view is given below.
package com.example.shara.booklistapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by shara on 12/17/2017.
*/
public class ListAdapter extends ArrayAdapter<Blist> {
public ListAdapter(#NonNull Context context, ArrayList<Blist> blists) {
super(context, 0, blists);
}
public String rslt;
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listitemview = convertView;
if (listitemview == null) {
listitemview = LayoutInflater.from(getContext()).inflate(R.layout.list_layout, parent, false);
}
Blist blist = getItem(position);
EditText search_query = listitemview.findViewById(R.id.search_query_text_view);
Button search_button = listitemview.findViewById(R.id.search_button1);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String searchquery = search_query.getText().toString();
}
});
ImageView bookthumbnail = listitemview.findViewById(R.id.thumbnail_imageview);
TextView title = listitemview.findViewById(R.id.title_textview);
TextView author = listitemview.findViewById(R.id.author_textview);
TextView publisher = listitemview.findViewById(R.id.publisher_texview);
return listitemview;
}
}
I am using another class named BookQueryUtils to create the URL and to do the HTTP request and JSON parsing.
I want to access the value of EditText view from BookQueryUtils class and then append it to the base URL.
Also how can I call the AsyncTaskLoader inside the BookQueryUtils class when the button is pressed. How can I do that?
Use Volley, example:
String url = "https://example.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
stringRequest.setTag("LOL");
queue.add(stringRequest);
I've created an acitvity that must have two pages. Those two pages shouldn't work like two different and unrelated activities, but like, let's say, one activity with two work area. Switching between them just with sliding right or left.
So I've impleneted it and switching works, but I can't get access to the object inside ViewPager.
Description:
Parent activity activity_setdetail.xml has two area: list view_setdetail_1.xml - of items and view_setdetail_2.xml - some settings. So, those two areas relate to different *.xml.
XMLs
activity_setdetail.xml
<android.support.v4.view.ViewPager
android:id="#+id/vpager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="2dp"
android:layout_marginEnd="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
view_setdetail_1.xml it goes to ViewPager vpager as right side area
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listViewOfWords"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginStart="2dp"
android:layout_marginTop="8dp"
android:clickable="true"
android:focusable="true"
android:paddingBottom="20dp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/txtToLBL"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txtToLBL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/view_goToSettings"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
view_setdetail_2.xml it goes to ViewPager vpager as left side area
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtCardsQTYinLessonlbl"
android:layout_width="0dp"
android:layout_height="38dp"
android:layout_marginLeft="2dp"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:gravity="center_vertical"
android:text="#string/txtCardsQTYinLessonLBLString"
android:textAlignment="center"
android:textColor="?attr/editTextColor"
android:textSize="16sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/etxtCardsQTYinLesson"
android:layout_width="34dp"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:ems="10"
android:imeOptions="actionDone"
android:inputType="number"
android:text="99"
android:textAlignment="center"
android:textSize="14sp"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toRightOf="#+id/txtCardsQTYinLessonlbl"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txtTolistLBL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/view_goToList"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
Resource file that enumerate screens for activity_setdetail.xml
public enum ResourcesModel {
FIRST_SCREEN(R.string.view_setdetail_1, R.layout.view_setdetail_1), SECOND_SCREEN(R.string.view_setdetail_2, R.layout.view_setdetail_2);
private int mTitleResourceId;
private int mLayoutResourceId;
ResourcesModel(int titleResId, int layoutResId) {
mTitleResourceId = titleResId;
mLayoutResourceId = layoutResId;
}
public int getTitleResourceId() {
return mTitleResourceId;
}
public int getLayoutResourceId() {
return mLayoutResourceId;
}
}
Adapter:
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import am.slotvin.hoodiesoft.by.enums.ResourcesModel;
public class SimplePagerAdapter extends PagerAdapter {
private Context mContext;
public SimplePagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup viewGroup, int position) {
ResourcesModel resources = ResourcesModel.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(
resources.getLayoutResourceId(), viewGroup, false);
viewGroup.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup viewGroup, int position, Object view) {
viewGroup.removeView((View) view);
}
#Override
public int getCount() {
return ResourcesModel.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ResourcesModel customPagerEnum = ResourcesModel.values()[position];
System.out.println("SimplePagerAdapter CharSequence getPageTitle" + position);
return mContext.getString(customPagerEnum.getTitleResourceId());
}
}
Java class for activity_setdetail.xml. I've reduced code just to only textview. But in reality I have ListView there and other stuff. Nevertheless, I can't influence even to textview.
public class SetDetail extends AppCompatActivity {
private String setName;
private int setID;
TextView txtToLBL;
SimplePagerAdapter spa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setName = getIntent().getStringExtra("setName");
setID = getIntent().getIntExtra("setID", 0);
setTitle(this.getString(R.string.activity_setdetailLabel) + setName);
setContentView(R.layout.activity_setdetail);
spa = new SimplePagerAdapter(this);
ViewPager viewPager = (ViewPager) findViewById(R.id.vpager);
if (viewPager != null) {
viewPager.setAdapter(spa);
}
txtToLBL = (TextView) findViewById(R.id.txtToLBL); //doesn't work
//txtToLBL.setText("bla-bla-bla"); //error - android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
LayoutInflater inflater = LayoutInflater.from(this);
View v = inflater.inflate(R.layout.view_setdetail_1, null, false);
txtToLBL = (TextView) v.findViewById(R.id.txtToLBL);
txtToLBL.setText("bla-bla-bla");//also doesn't work. No errors, just no changes.
}
}
So the question is - How to gegt access to elements on views that loaded in a ViewPager?
I found similar questions, but they didn't work for me.
UPDATE 1:
So, I've completely moved all code (also a bunch of listeners) to my SimplePagerAdapter. Now it should be renamed, because it is not universal anylonger and closely-coupled with the java class of parent activity. Looks not very good, but the only way I found at the moment. Though works OK, without freezing. Still be good to hear more elegant solution.
A ViewPager inflates 3 fragments at a time, the current fragment in view and a fragment on both left and right side of it. Since, your ViewPager has only two fragments both are inflated. So you can use something like viewPager.findViewById(resId) where resId is the Id of the view you want to access
I have the same kind of issue, the viewPager and the PagerAdapter should have been designed with a callback for when it's finished loading it's views. If I put code I want to run inside onPageSelected it all works, its just not available onCreate or onResume (presumably because the view is not instantiated by the pager yet.. If I had hair I'd be pulling it out trying to set default text on TextViews when my activity is Created...
I want to have a spinner which will contain a list of items.
The design I want is as follow:
I tried to put background for the spinner so now it only shows a background. I want white layout inside and with separator.
I tried to create a layout for the item and apply to the spinner but it gives error :
Process: com.kiranaapp, PID: 16697
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
My design now looks like this:
And onclick of spinner I get layout like this:
But I want the list to be shown onClick of TextInputLayout.
Here is Xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.kiranacustomerapp.Activities.SearchActivity"
tools:showIn="#layout/activity_search">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="20dp"
android:paddingTop="05dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#drawable/bg">
<Spinner
android:id="#+id/items_spinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#ffffff"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" />
</LinearLayout>
<android.support.design.widget.TextInputEditText
android:layout_width="240dp"
android:layout_height="45dp"
android:id="#+id/editTextItemName"
android:layout_gravity="center_horizontal"
android:hint="#string/item_name"
android:textSize="15sp"
android:padding="10dp" >
</android.support.design.widget.TextInputEditText>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_item_unit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="05dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp">
<android.support.design.widget.TextInputEditText
android:layout_width="240dp"
android:layout_height="45dp"
android:id="#+id/editTextItemUnit"
android:layout_gravity="center_horizontal"
android:hint="#string/unit"
android:textSize="15sp"
android:padding="10dp" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_item_quantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="05dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp">
<android.support.design.widget.TextInputEditText
android:layout_width="240dp"
android:layout_height="45dp"
android:id="#+id/editTextItemQuantity"
android:layout_gravity="center_horizontal"
android:hint="#string/quantity"
android:textSize="14sp"
android:padding="10dp" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<Button
android:layout_width="100dp"
android:layout_height="30dp"
android:text="Select"
style="?android:attr/borderlessButtonStyle"
android:id="#+id/buttonSelect"
android:layout_gravity="center_horizontal"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#drawable/btn_hlf_blue"
android:textColor="#android:color/white"
android:textSize="12sp" />
</LinearLayout>
</RelativeLayout>
Activity:
public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TextInputEditText edt_Item_Name,edt_Item_Unit,edt_Item_quantity;
private TextInputLayout textInput_Item_name,textInput_Item_Unit,textInput_Item_quantity;
private Spinner spinner;
private Button btnSelect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
setUpUI();
}
public void setUpUI(){
edt_Item_Name = (TextInputEditText) findViewById(R.id.editTextItemName);
edt_Item_quantity = (TextInputEditText)findViewById(R.id.editTextItemQuantity);
edt_Item_Unit = (TextInputEditText)findViewById(R.id.editTextItemUnit);
textInput_Item_name = (TextInputLayout)findViewById(R.id.input_layout_item_name);
textInput_Item_quantity = (TextInputLayout)findViewById(R.id.input_layout_item_quantity);
textInput_Item_Unit = (TextInputLayout)findViewById(R.id.input_layout_item_unit);
spinner = (Spinner)findViewById(R.id.items_spinner);
btnSelect = (Button)findViewById(R.id.buttonSelect);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.items_array, R.layout.order_item_layout);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
textInput_Item_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
spinner.setVisibility(View.VISIBLE);
edt_Item_Unit.setVisibility(View.GONE);
edt_Item_quantity.setVisibility(View.GONE);
btnSelect.setVisibility(View.GONE);
textInput_Item_name.setBackgroundResource(R.drawable.purple_bg);
}
});
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
How can I achieve this design? Can anyone help with this please? Thank you..
Use ListView or RecyclerView and put a spinner in a layout that will be use in your viewholder.class associated with getView method in adapter class, after-that set your data using ArrayList/Hashmap with the help of constructor of Adapter class.
Follow this
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Use this layout
<?xml version="1.0" encoding="utf-8"?>
<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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"/>
</LinearLayout>
Draw your layout somthing like this:
<RelativeLayout
android:id="#+id/spinner_layout"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_30"
android:layout_margin="#dimen/dp_20"
android:background="#color/fragment_bg"
android:orientation="horizontal">
<TextView
android:id="#+id/txt_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="#dimen/dp_20"
android:hint="#string/select_city"
android:singleLine="tru
android:textSize="#dimen/sp_15"/>
<Spinner
android:id="#+id/spinner_city"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_30"
android:layout_centerVertical="true"
android:entries="#array/StateName"
android:gravity="center"
android:padding="#dimen/sp_15"
app:binding="#{location.locations}"/>
</RelativeLayout>
and use your textinput layout instead of textview
Don't use Edittext use Textview to set clicked item text. "if you use edittext, then you have to tap two times to get call in onClickListener method because on first time of click it set to get focus and open soft keyboard"
So, I'm trying to create a screen that when clicking a button this takes the data from some EditText and add them to a ListView item, now I know there are a lot of examples on the web and I've done them and they work, but when I took them to what I want to do it just adds one item and stops working it doesn't throw any exception or anything, it just add one item, this is what I got so far...
create_class.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.eduardolaguna.mariela.app.activities.CreateClass">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/cc_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/cc_hint_class_name" />
<View
android:id="#+id/cc_divider1"
style="#style/Divider"
android:layout_below="#+id/cc_name" />
<TextView
android:id="#+id/tv_cc_professors_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/cc_divider1"
android:text="#string/cc_tv_professors_data" />
<EditText
android:id="#+id/cc_professors_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_cc_professors_data"
android:hint="#string/cc__hint_professors_name"
android:inputType="textPersonName|textAutoComplete|textAutoCorrect" />
<EditText
android:id="#+id/cc_professors_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_professors_name"
android:hint="#string/cc_hint_professors_email"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/cc_professors_phonenumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_professors_email"
android:hint="#string/cc_hint_professors_phonenumber"
android:inputType="phone" />
<View
android:id="#+id/cc_divider2"
style="#style/Divider"
android:layout_below="#id/cc_professors_phonenumber" />
<TextView
android:id="#+id/tv_cc_schedule"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_divider2"
android:text="#string/cc_tv_class_schedule" />
<Spinner
android:id="#+id/sp_cc_day_of_the_week"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_cc_schedule"
android:entries="#array/dow" />
<EditText
android:id="#+id/cc_from_schedule"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/sp_cc_day_of_the_week"
android:hint="#string/cc_hint_from_schedule"
android:inputType="time" />
<EditText
android:id="#+id/cc_to_schedule"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="#id/sp_cc_day_of_the_week"
android:layout_toRightOf="#id/cc_from_schedule"
android:hint="#string/cc_hint_to_schedule"
android:inputType="time" />
<EditText
android:id="#+id/cc_floor_number"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="#id/sp_cc_day_of_the_week"
android:layout_toRightOf="#id/cc_to_schedule"
android:hint="#string/cc_hint_floor"
android:inputType="number" />
<EditText
android:id="#+id/cc_classroom"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="#id/sp_cc_day_of_the_week"
android:layout_toRightOf="#id/cc_floor_number"
android:hint="#string/cc_hint_classroom" />
<Button
android:id="#+id/btn_cc_add_schedule"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/cc_from_schedule"
android:text="#string/cc_add_schedule" />
<ListView
android:id="#+id/cc_schedule_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btn_cc_add_schedule" />
</RelativeLayout>
</ScrollView>
</LinearLayout>
schedule_item.xml
<?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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/sch_day_of_the_week"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="MiƩrcoles"
android:textSize="60dp" />
<TextView
android:id="#+id/sch_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="5:45"
android:textSize="20dp" />
<TextView
android:id="#+id/sch_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="7:15"
android:textSize="20dp" />
<TextView
android:id="#+id/sch_floor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="7"
android:textSize="20dp" />
<TextView
android:id="#+id/sch_clasroom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="lab1"
android:textSize="20dp" />
</LinearLayout>
ScheduleAdapter.java
public class ScheduleAdapter extends ArrayAdapter<Actividad> {
private int layoutResourceId;
private LayoutInflater inflater;
private List<Actividad> shifts;
public ScheduleAdapter(Context context, int resource, List<Actividad> objects) {
super(context, resource, objects);
layoutResourceId = resource;
shifts = objects;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
Holder holder = null;
row = inflater.inflate(layoutResourceId, null);
holder = new Holder();
holder.actividad = shifts.get(position);
holder.dow = (TextView) row.findViewById(R.id.sch_day_of_the_week);
holder.fromTXT = (TextView) row.findViewById(R.id.sch_from);
holder.toTXT = (TextView) row.findViewById(R.id.sch_to);
holder.floorTXT = (TextView) row.findViewById(R.id.sch_floor);
holder.roomTXT = (TextView) row.findViewById(R.id.sch_clasroom);
setupItem(holder);
row.setTag(holder);
return row;
}
private void setupItem(Holder holder) {
holder.dow.setText(holder.actividad.getDiaDeLaSemana());
holder.fromTXT.setText(holder.actividad.getDesdeStr());
holder.toTXT.setText(holder.actividad.getHastaStr());
holder.floorTXT.setText(holder.actividad.getPiso());
holder.roomTXT.setText(holder.actividad.getSalon());
}
public static class Holder {
Actividad actividad;
TextView dow;
TextView fromTXT;
TextView toTXT;
TextView floorTXT;
TextView roomTXT;
}
}
And finally the CreateClass.java
public class CreateClass extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_class);
ListView view = (ListView) findViewById(R.id.cc_schedule_list);
final ScheduleAdapter adapter = new ScheduleAdapter(getApplicationContext(), R.layout.schedule_item, new ArrayList<Actividad>());
view.setAdapter(adapter);
Button addSchedule = (Button) findViewById(R.id.btn_cc_add_schedule);
addSchedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Resources res = getResources();
ListView scheduleView = (ListView) findViewById(R.id.cc_schedule_list);
ScheduleAdapter adapter1 = (ScheduleAdapter) scheduleView.getAdapter();
Actividad act = new Actividad(TipoEvento.CLASE);
Spinner dow = (Spinner) findViewById(R.id.sp_cc_day_of_the_week);
act.setDiaDeLaSemana(dow.getSelectedItem().toString());
TextView from = (TextView) findViewById(R.id.cc_from_schedule);
act.setDesdeStr(res.getString(R.string.from) + ": " + from.getText().toString());
TextView to = (TextView) findViewById(R.id.cc_to_schedule);
act.setHastaStr(res.getString(R.string.to) + ": " + to.getText().toString());
TextView floor = (TextView) findViewById(R.id.cc_floor_number);
act.setPiso(res.getString(R.string.floor) + ": " + floor.getText().toString());
TextView classroom = (TextView) findViewById(R.id.cc_classroom);
act.setSalon(res.getString(R.string.classroom) + ": " + classroom.getText().toString());
adapter1.add(act);
}
});
}
}
You should instantiate your adapter with the Activity context, not the application context.
Storing a copy of the constructed list in shifts can be dangerous.
Don't store shifts in the Holder. Only views go in there.
When populating the convertView, reference the internal getItem(position) method to obtain the Actividad data...not your shifts variable.
You're also using the ViewHolder paradigm incorrectly. Example here.
Turns out the problem is the ListView is inside the ScrollView, this does not work properly when the list grows dynamically, I move it out the ScrollView and it works like a charm.
This was according to #Romain Guy a developer in the Android project, where he stated that
Using a ListView to make it not scroll is extremely expensive and goes against the whole purpose of ListView. You should NOT do this. Just use a LinearLayout instead.
So I use a LinearLayout to draw the new items on the layout.