Please bear with me as I am new to android studio. I want to make a ScrollView containing images with corresponding name (TextView). I want to be able to select an image by touching it in the ScrollView, but I don't know how. I have implemented the ScrollView like this, I also want to be able to add pictures with a name attached to them.
Main_activity.xml
<HorizontalScrollView
android:id="#+id/scrollFilterView"
android:layout_width="fill_parent"
android:layout_height="130dp"
android:scrollbars="none"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.57"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<LinearLayout
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" />
</HorizontalScrollView>
scrollview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/filterView"
android:layout_width="90dp"
android:layout_height="90dp"
app:srcCompat="#android:drawable/sym_def_app_icon"
android:contentDescription="filterView" />
<TextView
android:id="#+id/textFilter"
android:layout_width="90dp"
android:gravity="center"
android:layout_height="wrap_content"
android:text="textFilter" />
MainActivity.java
LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < NUMBER_OF_FILTERS_GRID; i++ ) {
View scrollView = inflater.inflate(R.layout.scrollview, gallery, false);
TextView textview = scrollView.findViewById(R.id.textFilter);
textview.setText("Filter "+ i);
ImageView filterView = scrollView.findViewById(R.id.filterView);
filterView.setImageResource(R.mipmap.ic_launcher);
gallery.addView(scrollView);
}
}
Some input to if this is the right path to take and what functions i should use is very appreciated :)
Use a RecyclerView instead of a ListView, and used with and adapter, this will grant you more control over each item displayed on the list (in this case in the RecyclerView),
you will need to create and Adapter class, a simple class for your Items and a new XML layout that will serve as the model of each item in the list.
Simple class for your items:
public class dataSetItem {
private Integer image;
private String listItemText;
public Integer getImage() {
return image;
}
public void setImage(Integer image) {
this.image = image;
}
public String getListItemText() {
return listItemText;
}
public void setListItemText(String listItemText) {
this.listItemText = listItemText;
}
}
In your mainActivity remove the listView and for loop, use this instead:
public class MyActivity extends Activity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList mAdapter = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
recyclerView = (RecyclerView) findViewById(R.id.your_recycler_view);
mDataset.add(dataSetItem("item 1", R.mipmap.ic_launcher))
mDataset.add(dataSetItem("item 2", R.mipmap.ic_launcher))
// You can add more items to the mDataset list and call the adapter again to update the RecyclerView
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
recyclerView.setAdapter(mAdapter);
}
// ...
}
Create this XML layout which will serve as the model for each item, called my_item_list_layout:
<?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:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<ImageView
android:id="#+id/the_image_i_want_to_click"
android:layout_width="80dp"
android:layout_margin="10dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:background="#color/ADRBlack"
/>
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="220dp"
android:textColor="#color/Black"
android:textSize="16sp"
tools:text="Example Restaurant" />
</LinearLayout>
</LinearLayout>
Now the adapter class, in this case called MyAdapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private customItem[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView textView;
public MyViewHolder(TextView v) {
super(v);
textView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(customItem[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.my_item_list_layout, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.textView.setText(mDataset[position].getListItemText);
holder.textView.setBackground(mDataset[position].getImage);
//Now to do something when you clic the image use this
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//Your action here
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
}
Related
I am a new Programmer, actually I was trying to make an app. I was trying to make an activity that uses RecyclerView to Show TextInputEditText with spinner and TextView. It means that I was trying to make an activity that uses Recyclerview and In the layout of Recycler View, I have used Text Input Edit Text and Spinner and TextView. I have put these three in a single layout. But the main problem that I facing is that when I launch my app with my code then it remains blank activity it is not showing TextInputEditText nor spinner and nor TextView.
So the conclusion is I want to show [TextInputEditText, Spinner and TextView] in RecyclerView But my code is returning Blank Activity.
Here is my code:-
It is my adapter class:-
public class SpecialHoursAdapter extends RecyclerView.Adapter<SpecialHoursAdapter.SpecialHourHolder> {
// private ArrayList[] mDataSet;
private List<SpecialHorusModal> modal = new ArrayList<>();
private Context context;
public SpecialHoursAdapter(Context context) {
this.context = context;
}
#NonNull
#Override
public SpecialHourHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.special_hours_layout_card, parent, false);
return new SpecialHourHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SpecialHourHolder holder, int position) {
}
#Override
public int getItemCount() {
return modal.size();
}
public static class SpecialHourHolder extends RecyclerView.ViewHolder {
private TextInputEditText editText;
private Spinner spinner;
private TextView textView;
public SpecialHourHolder(#NonNull View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.special_hours_editor);
spinner = itemView.findViewById(R.id.spinner_special_hours_date);
textView = itemView.findViewById(R.id.time_picker_special_horus);
}
}
}
It is My MainActivity:-
public class SpecialHoursActivity extends AppCompatActivity {
private RecyclerView containerRecyclerView;
private RecyclerView.LayoutManager first, container;
private SpecialHoursAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_horus);
// mainRecyclerView = findViewById(R.id.activity_special_horus_main_recyclerview);
containerRecyclerView = findViewById(R.id.layout_container_recyclerview_special_hours);
// mainRecyclerView.setHasFixedSize(true);
containerRecyclerView.setHasFixedSize(true);
first = new LinearLayoutManager(this);
container = new LinearLayoutManager(this);
// mainRecyclerView.setLayoutManager(first);
containerRecyclerView.setLayoutManager(container);
containerRecyclerView.setAdapter(adapter);
}
}
Here is my RecyclerView Layout:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/special_hours_editor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Special Hours"
android:inputType="text"
android:maxLength="20" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Spinner
android:id="#+id/spinner_special_hours_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/time_picker_special_horus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:text="00:00" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
My Main Layout -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_special_horus_main_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/layout_container_recyclerview_special_hours"
android:orientation="vertical"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
I have not used any modal class because I don't know how to use it with Widgets.
you need to pass the data to your adapter
public SpecialHoursAdapter(Context context,List<SpecialHorusModal> data) {
this.context = context;
this.model=data; //it will show your recyclerview
}
we could not show the Recyclerview with empty data
You need to populate the data your Adapter holds, adapter with empty data will obviously show no items.
public class SpecialHoursAdapter extends RecyclerView.Adapter<SpecialHoursAdapter.SpecialHourHolder> {
private List<SpecialHorusModal> items = new ArrayList<>();
private Context context;
public SpecialHoursAdapter(Context context) {
this.context = context;
}
//Call this in onClick of your button, passing it the object to add
public void addItem(SpecialHoursModal item) {
items.add(item);
notifyDataSetChange(); //This is important
}
#NonNull
#Override
public SpecialHourHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.special_hours_layout_card, parent, false);
return new SpecialHourHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SpecialHourHolder holder, int position) {
//Bind the data to view for the object at this position
SpecialHorusModal item = items.get(position);
//...
}
#Override
public int getItemCount() {
return items.size();
}
public static class SpecialHourHolder extends RecyclerView.ViewHolder {
private TextInputEditText editText;
private Spinner spinner;
private TextView textView;
public SpecialHourHolder(#NonNull View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.special_hours_editor);
spinner = itemView.findViewById(R.id.spinner_special_hours_date);
textView = itemView.findViewById(R.id.time_picker_special_horus);
}
}
}
When your button is clicked, or you need to add an item:
adapter.addItem(new SpecialHorusModal(...));
I'm new to Android Studio and coding in general and I am trying to display a custom ListView with an image of a colour and the name of the colour. I have used a custom Adapter to inflate the view with two arrays containing the drawable image colours and string of the names.
The problem I am having - the custom adapter is only displaying the layers from position 1 and onwards. For example, where the first layer should be img_01 and "red" - it is displaying img_02 and "Orange".
I've tried debugging the code and it seems that though the adapter is setting the values for position 0, but I cannot find the reason why it is not displaying (as the others are displaying fine).
The images & names are just placeholders, so an alternative solution that doesn't include both the drawables and names wouldn't be viable,
Thank you in advance
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
int[] images;
String[] colour;
LayoutInflater mInflater;
public CustomAdapter(Context c, int[] i, String[] col) {
this.context = c; //sets the application context that has been passed to the adapter
this.images = i; //sets the images array that has been passed to the adapter
this.colour = col; //sets the colour array that has been passed to the adapter
mInflater = (LayoutInflater.from(context)); //sets the layout inflater from context
}
#Override
public int getCount() { //total number of elements in the array
return images.length;
}
#Override
public Object getItem(int position) { //gets the item using the position
return null;
}
#Override
public long getItemId(int position) { //gets the item position
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) { //this is used to update the view
convertView = mInflater.inflate(R.layout.custom_layout, null);
ImageView image = convertView.findViewById(R.id.imageView);
TextView text = convertView.findViewById(R.id.textView);
text.setText(colour[position]);
image.setImageResource(images[position]);
return convertView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView mListView;
int[] images = {R.drawable.img01,
R.drawable.img02,
R.drawable.img03,
R.drawable.img04};
String[] colour = {"Red",
"Orange",
"Yellow",
"Green"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), images, colour);
//passes information of images and application context to the item adapter
mListView.setAdapter(customAdapter);
//sets the adapter to the listview
}
}
custom_layout.xml
<?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"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="7dp"
android:layout_marginLeft="7dp"
android:layout_marginTop="9dp"
app:srcCompat="#drawable/img01" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="99dp"
android:layout_marginLeft="99dp"
android:layout_marginTop="36dp"
android:text="colourName" />
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try to set the height of the ListView to wrap_content instead of hardcoding it
<ListView
...
android:layout_height="wrap_content"/>
You can do it with RecyclerView.
Create a custom class
public class ExampleItem {
private int mImageResource; //your color image
private String mText1; //your text
public ExampleItem(int imageResource, String text1) {
mImageResource = imageResource;
mText1 = text1;
}
public int getImageResource() {
return mImageResource;
}
public String getText1() {
return mText1;
}
}
Create a XML layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
app:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="2dp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:text="Line 1"
android:textColor="#android:color/black"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Create a Recycler View Adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mTextView1 = itemView.findViewById(R.id.textView);
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
your activity_main.xml
<?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"
tools:context="com.example.application.recyclerviewproject.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
android:padding="4dp"
android:scrollbars="vertical" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ExampleItem> exampleList = new ArrayList<>();
exampleList.add(new ExampleItem(R.drawable.img01, "Red"));
exampleList.add(new ExampleItem(R.drawable.img02, "Orange"));
exampleList.add(new ExampleItem(R.drawable.img03, "Yellow"));
exampleList.add(new ExampleItem(R.drawable.img04, "Green"));
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(exampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
I want select optionally one image like radio button and put tick mark on that image. How can i do it.Here I add my adapter class and xml file
This is my adapter class.
public class StarCountAdapter extends RecyclerView.Adapter<StarCountAdapter.StarCountHolder> {
Context context;
LayoutInflater inflater;
List<StarCount> starCounts = new ArrayList<>();
public StarCountAdapter(Context context, List<StarCount> starCounts) {
this.context = context;
this.inflater = LayoutInflater.from(context);
this.starCounts = starCounts;
}
#Override
public StarCountHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.star_count_row,parent,false);
return new StarCountHolder(view);
}
#Override
public void onBindViewHolder(StarCountHolder holder, int position) {
StarCount model = starCounts.get(position);
Picasso.with(context)
.load("http://"+model.getImagePath())
.into(holder.starImage);
holder.actorName.setText(model.getName());
holder.counts.setText(""+model.getCount());
}
#Override
public int getItemCount() {
return starCounts.size();
}
public class StarCountHolder extends RecyclerView.ViewHolder {
ImageView starImage;
TextView actorName,counts;
public StarCountHolder(View itemView) {
super(itemView);
starImage = (ImageView) itemView.findViewById(R.id.starCountIv);
actorName = (TextView) itemView.findViewById(R.id.acterName);
counts = (TextView) itemView.findViewById(R.id.counts);
}
}
}
This is my star_count_row.xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/starCountIv"
android:layout_width="match_parent"
android:layout_height="175dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:orientation="vertical">
<TextView
android:id="#+id/acterName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000" />
<TextView
android:id="#+id/counts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000" />
</LinearLayout>
</RelativeLayout>
Thank You.
create custom radio button followin link here you will get your answer
Adding custom radio buttons in android
I have a simple listView via a custom adapter. Each row in the list view is composed of a ImageButton and TextView.
The idea is to change the ImageButton when user taps on it and it does not work. However, ImageButton changes for the views that are scrolled and recycled. I mean, when user scrolls down the list and comes back to the top and tap on the ImageButton it works as expected for those rows that were scrolled and back again.
Can you guys help me out what i'm missing? I'm extremely new to Android and have been stuck around this for about a week now trying to fix this.
Here's the APK for the sample test app:
https://www.dropbox.com/s/pzlahtqkgj010m8/app-ListViewExample.apk?dl=0
Here are the relevant parts of my code:
avtivity_main.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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
/>
</RelativeLayout>
and to render the single row in the ListView the following xml is utilized:
single_row.xml
<?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:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:src="#drawable/b"
android:layout_weight="2"
style="#style/ListView.first"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_weight="10"
android:layout_gravity="center"
/>
</LinearLayout>
coming to the Java code,
MainActivity.java is
public class MainActivity extends AppCompatActivity {
String[] titles;
ListView list;
private listViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
titles = res.getStringArray(R.array.titles);
list = (ListView) findViewById(R.id.listView);
adapter = new listViewAdapter(this, titles);
list.setAdapter(adapter);
}
}
and the custom adapter listViewAdapter.java look like this
class sListItem {
public ImageButton button;
public TextView text;
public boolean active;
}
public class listViewAdapter extends ArrayAdapter<String> {
private final String[] titles;
Context context;
private int size = 15;
public sListItem mp[] = new sListItem[size];
public listViewAdapter(Context context, String[] titles) {
super(context, R.layout.single_row, R.id.imageButton, titles);
this.context = context;
this.titles = titles;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, parent, false);
if(mp[position] == null)
mp[position] = new sListItem();
mp[position].button = (ImageButton) row.findViewById(R.id.imageButton);
mp[position].button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp[position].active = !mp[position].active;
setIcon(position, mp[position].active);
}
});
mp[position].text = (TextView) row.findViewById(R.id.textView);
mp[position].text.setText(titles[position]);
setIcon(position, mp[position].active);
return row;
}
private void setIcon(int position, boolean active) {
Drawable drawable;
if(active){
drawable = getContext().getResources().getDrawable(R.drawable.a);
} else {
drawable = getContext().getResources().getDrawable(R.drawable.b);
}
mp[position].button.setImageDrawable(drawable);
}
}
EDIT: Added link to sample test app.
You should tell adapter to update by calling notifydatasetchanged in the click listener
mp[position].button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp[position].active = !mp[position].active;
setIcon(position, mp[position].active);
notifydatasetchanged();
}
});
I'm completely new to Java/Android and am stuck with listviews.
What I want is to have 4 lines in a row in listview with different font styles
rowlayout.xml
<TextView
android:id="#+id/1"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/2"
android:textSize="30sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/3"
android:typeface="sans"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/4"
android:typeface="sans"
android:textSize="15sp"
android:textStyle="italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
I have this in a separate xml file
results.xml
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/TitleLbl" >
</Listview>
and my array adapter looks like this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.rowlayout, R.id.2, Array);
setListAdapter(adapter);
What I'm trying to do is get an arraylist (containing ID, name, surname and number) to populate the listview so that each information is on its own line in the row.
the array adapter above works, but each of the four informations is in their own row.
Can anyone help?
(also, I've scoured the internet to try and sort this out, but can't seem to find anything that helps me)
You may need to use custom list view with custom array adapter. Refer this link for example.
Content:
The Android HelloListView ( http://developer.android.com/resources/tutorials/views/hello-listview.html ) tutorial shows how to bind a ListView to an array of string objects, but you'll probably outgrow that pretty quickly. This post will show you how to bind the ListView to an ArrayList of custom objects, as well as create a multi-line ListView.
Let's say you have some sort of search functionality that returns a list of people, along with addresses and phone numbers. We're going to display that data in three formatted lines for each result, and make it clickable.
First, create your new Android project, and create two layout files. Main.xml will probably already be created by default, so paste this in:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:text="Custom ListView Contents"
android:gravity="center_vertical|center_horizontal"
android:layout_width="fill_parent" />
<ListView
android:id="#+id/ListView01"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
Next, create a layout file called custom_row_view.xml. This layout will be the template for each individual row in the ListView. You can use pretty much any type of layout - Relative, Table, etc., but for this we'll just use Linear:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/name"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#FFFF00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/cityState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Now, add an object called SearchResults. Paste this code in:
public class SearchResults {
private String name = "";
private String cityState = "";
private String phone = "";
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCityState(String cityState) {
this.cityState = cityState;
}
public String getCityState() {
return cityState;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
This is the class that we'll be filling with our data, and loading into an ArrayList.
Next, you'll need a custom adapter. This one just extends the BaseAdapter, but you could extend the ArrayAdapter if you prefer.
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtCityState = (TextView) convertView.findViewById(R.id.cityState);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtCityState.setText(searchArrayList.get(position).getCityState());
holder.txtPhone.setText(searchArrayList.get(position).getPhone());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtCityState;
TextView txtPhone;
}
}
(This is basically the same as the List14.java API demo)
Finally, we'll wire it all up in the main class file:
public class CustomListView extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<SearchResults> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResults));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(ListViewBlogPost.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1.setName("John Smith");
sr1.setCityState("Dallas, TX");
sr1.setPhone("214-555-1234");
results.add(sr1);
sr1 = new SearchResults();
sr1.setName("Jane Doe");
sr1.setCityState("Atlanta, GA");
sr1.setPhone("469-555-2587");
results.add(sr1);
sr1 = new SearchResults();
sr1.setName("Steve Young");
sr1.setCityState("Miami, FL");
sr1.setPhone("305-555-7895");
results.add(sr1);
sr1 = new SearchResults();
sr1.setName("Fred Jones");
sr1.setCityState("Las Vegas, NV");
sr1.setPhone("612-555-8214");
results.add(sr1);
return results;
}
}
Notice that we first get an ArrayList of SearchResults objects (normally this would be from an external data source...), pass it to the custom adapter, then set up a click listener. The listener gets the item that was clicked, converts it back to a SearchResults object, and does whatever it needs to do.