I have a template layout which represents each of my rows in a ListView in my app.
Here is the photorow.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/bodylay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/leftbigsquare"
android:layout_width="0dp"
android:layout_height="140dp"
android:layout_weight="1"
android:background="#1000b0"
android:src="#drawable/test1"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#d0b0b0"
android:textSize="15sp" >
<ImageView
android:id="#+id/righttupperleft"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#b170b0"
android:src="#drawable/test1" />
<ImageView
android:id="#+id/rightupperright"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="1"
android:background="#b110b0"
android:src="#drawable/test1" />
</LinearLayout>
<ImageView
android:id="#+id/righthorizontal"
android:layout_width="match_parent"
android:layout_height="70dp"
android:src="#drawable/test1" />
</LinearLayout>
It is repeated row by row. What I want to do is to change "ImageView" child, when I load the image from my server not redesign the row layout each time. Each row will show different "leftbigsquare", "rightupperleft", "rightupperright", "righthorizontal" (look at ImageViews ids) photos.
I researched and saw some examples, but they did that by hardcoding the layout such as :
LinearLayout A = new LinearLayout(this);
A.setOrientation(LinearLayout.HORIZONTAL);
I want to use my photorow.xml as template and just change its attributes such as source in each row.
Is it possible to use my photorow.xml as the template of a row ?
EDIT
My custom adapter :
package com.example.test2;
import java.util.List;
import com.squareup.picasso.Picasso;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class PhotoAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<PhotoRow> rowList;
Activity context = null;
public PhotoAdapter(Activity activity, List<PhotoRow> rows) {
mInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowList = rows;
context = activity;
}
#Override
public int getCount() {
return rowList.size();
}
#Override
public Object getItem(int position) {
return rowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
rowView = mInflater.inflate(R.layout.photorow, null);
//Here I get the ImageView of my photorow xml
ImageView leftBigSquare = (ImageView) rowView
.findViewById(R.id.leftbigsquare);
// Here I get the proper URL from rowList by using Picasso framework
Picasso.with(context).load(rowList.get(position).getUrls().get(0))
.resize(50, 50).centerCrop().into(leftBigSquare);
//So how can I put the leftBigSquare ImageView to my photorow template with its proper attributes
return rowView;
}
}
Yes, of course, you can use same rowview XML and still have different data in every row.
You must use a custom adapter and then inflate your row s from that adapter and based on several conditions change your data.
Paste your custom adapter code and I will show you how to do it.
Related
i have one list view with two text views inside it, one edit text that is in the same activity but not in the list view and two buttons one to add to the list view and the other to delete from it.
how to add integers to the first text view, the sum of all integers to the second one, and to be from a custom adapter.
thank you.
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"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="#+id/edit_ten"
android:hint="Score"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn_add"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Add"/>
<Button
android:id="#+id/btn_delete"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Undo"/>
</LinearLayout>
<ListView
android:id="#+id/list_sinhvien"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
item_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"
android:orientation="horizontal">
<LinearLayout
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_ten"
android:textSize="20dp"
android:text="Score"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/text_sdt"
android:textSize="20dp"
android:text="Total"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.example.addanddelete;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView listSinhvien;
EditText editTen;
Button btnThem , btnSua;
ArrayList<Sinhvien> arraySinhvien;
CustomAdapter myadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anhxa();
arraySinhvien = new ArrayList<Sinhvien>();
myadapter = new CustomAdapter(this , R.layout.item_layout,arraySinhvien);
listSinhvien.setAdapter(myadapter);
btnSua.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int count = myadapter.getCount();
myadapter.remove(myadapter.getItem(count -1));
myadapter.notifyDataSetChanged();
return;}});
}
private void anhxa(){
listSinhvien = (ListView)findViewById(R.id.list_sinhvien);
editTen = (EditText)findViewById(R.id.edit_ten);
btnThem = (Button)findViewById(R.id.btn_add);
btnSua = (Button)findViewById(R.id.btn_undo);
btnThem.setOnClickListener(this);
btnSua.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_add:
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
String ten = editTen.getText().toString();
String sdt = editTen.getText().toString();
Sinhvien temp = new Sinhvien(R.mipmap.ic_launcher,ten , sdt);
arraySinhvien.add(temp);
myadapter.notifyDataSetChanged();
break;
}
}
}
CustomAdapter.java
package com.example.addanddelete;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter {
Activity activity;
int layout;
ArrayList<Sinhvien> arrSinhVien;
public CustomAdapter(#NonNull Activity activity, int layout, #NonNull ArrayList<Sinhvien> arrSinhVien) {
super(activity, layout, arrSinhVien);
this.activity = activity;
this.layout = layout;
this.arrSinhVien = arrSinhVien;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
convertView = layoutInflater.inflate(layout, null);
TextView ten = (TextView) convertView.findViewById(R.id.text_score);
TextView sdt = (TextView) convertView.findViewById(R.id.text_total);
ten.setText(arrSinhVien.get(position).getTenSinhvien());
sdt.setText(arrSinhVien.get(position).getSdtSinhvien());
return convertView;
}
}
Sinhvien.java
package com.example.addanddelete;
public class Sinhvien {
String tenSinhvien;
String sdtSinhvien;
public Sinhvien(String iclauncher,String ten, String sdt) {
}
public Sinhvien(int iclauncher,String tenSinhvien, String sdtSinhvien) {
this.tenSinhvien = tenSinhvien;
this.sdtSinhvien = sdtSinhvien;
}
public String getTenSinhvien() {
return tenSinhvien;
}
public void setTenSinhvien(String tenSinhvien) {
this.tenSinhvien = tenSinhvien;
}
public String getSdtSinhvien() {
return sdtSinhvien;
}
public void setSdtSinhvien(String sdtSinhvien) {
this.sdtSinhvien = sdtSinhvien;
}
}
The general behaviour/implementation that you've outlined in your question is very well documented. That said, I'd suggest considering utilising a RecyclerView with associated custom item view and adapter, as opposed to a ListView. There are a few reasons why I'd suggest this.
I did a little searching and found several examples that cover the general idea of your implementation. This example does a great job of illustrating how to achieve what you're seeking. The article begins by outlining some reasons to work with a RecyclerView over a ListView or GridView, then proceeds to give an in-depth run-down on how to implement a RecyclerView with custom adapter (and associated item view and item class).
At a glance, your implementation would require:
An Activity containing your RecyclerView, two Buttons (used for adding and deleting elements from the RecyclerView) and an EditText for taking user input.
A custom item View representing individual items of your RecyclerView list. This would contain the two TextView views (one for displaying the integer and the other for displaying the sum of all integers).
A custom item model Class to represent the data model for the above custom item View. This would hold an integer value and likely some logic for displaying the sum.
A custom RecyclerView adapter (which ties all of the above together). This will need to handle the task of binding data from your dataset (that grows and shrinks based on user input) to instances of your custom items that are to appear in the RecyclerView list. This adapter could also be used by your add and delete item buttons to modify the elements in the RecyclerView list.
The above is outlined in far greater depth in the link I provided earlier.
I sincerely hope that helps!
Currently working to develop a custom adapater, to display data on a list row as follows:
|TextView| |TextView| |TextView| |TextView|
Currently I am using this tutorial for reference.
http://www.ezzylearning.com/tutorial.aspx?tid=1763429
However, as mentioned, I encounter a problem with the customeradapter, specifically when creating an inflator and in also identifying the ID for Textview in the custom row xml.
Here are the two lines that throw up errors:
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
&
holder.food = (TextView)row.findViewById(R.id.foodName);
Errors given are: LayoutInflater cannot be resolved to a type & R cannot be resolved to a variable.
Many thanks for any suggestions.
Imports
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.view.LayoutInflater;
My full implementation for the adapter:
public class CustomBaseAdapter extends ArrayAdapter<ReportSummary>{
private Context context;
private int layoutResourceId;
private List<ReportSummary> report = new ArrayList<ReportSummary>();
public CustomBaseAdapter(Context context, int layoutResourceId, List<ReportSummary> report) {
super(context, layoutResourceId, report);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.report = report;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.food = (TextView)row.findViewById(R.id.foodName);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
holder.food.setText(report.get(0).getFoodName());
holder.status.setText(report.get(0).getStatus());
//holder.foodRDA.setText(report.get(0).getStatus());
holder.userLvl.setText(report.get(0).getLevel());
return row;
}
class ViewHolder {
TextView food;
TextView status;
TextView userLvl;
TextView foodRDA;
TextView difference;
}
}
XML layouts
activity_diet_analysis
<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: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=".DietAnalysisActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
row_diet_analysis
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:id="#+id/foodName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:text="TTTT"
/>
<TextView android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/foodName"
android:text="TJJDFDFDF"
/>
<TextView android:id="#+id/foodRDA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/status"
android:text="TTTT"
/>
<TextView android:id="#+id/userLvl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/foodRDA"
android:text="TTTT"
/>
<TextView android:id="#+id/difference"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/userLvl"
android:text="TTTT"
/>
</RelativeLayout>
Based on the errors you mentioned, you probably need to import LayoutInflator:
import android.view.LayoutInflater;
And import the generated R file for your app:
import com.example.app.R
Be sure you import the correct R file too, not android.R.
Also, if you're using an IDE such as Eclipse or Android Studio (which you probably should be), it will do this for you automatically.
Note that the R file will not be generated for your project if you have any errors in your resources files.
Update: Simpler code created and presented here, full layout XML definitions.
When trying to replace the row layout with the icon on the left by the new drawableStart attribute of the TextView element in XML layout, I can observe the following wrongly displayed last item (captured on Nexus 7):
The related code is -- MainActivity:
package cz.skil.android.tut.testtextviewdrawablestart;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
ListView listView = (ListView) findViewById(R.id.mylist);
String[] values = new String[] {"item 1", "item 2", "item 3"};
MyAdapter adapter = new MyAdapter(this, values);
listView.setAdapter(adapter);
}
}
MyAdapter
package cz.skil.android.tut.testtextviewdrawablestart;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyAdapter(Context context, String[] values) {
super(context, R.layout.row, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.mylabel);
textView.setText(values[position]);
return rowView;
}
}
The main_list.xml layout:
<?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" >
<ListView
android:id="#+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content" > <!-- Update: here is the bug -->
</ListView>
</LinearLayout>
and finally the row.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mylabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="4dp"
android:drawablePadding="8dp"
android:drawableStart="#drawable/reminder"
android:lines="1"
android:textSize="24sp" >
</TextView>
I guess the reason is that the height of the area for displaying the items is calculated from dimensions declared for the text; however, the icon possibly forces a bigger height for the list item.
Can you confirm the behaviour? If yes, why it behaves so? I am new to Android. It is likely I am doing it wrongly.
(The question is loosely related to this one: Android layout: on TextView and android:drawableStart -- setting size of the icon?).
It's always wrong to set android:layout_height="wrap_content" for a ListView. It works as expected with android:layout_height="fill_parent". More detailed explanation could be found here The World of ListView
Though I don't know if this is intended behaviour or bug, this happens when you use drawableStart. Change it to drawableLeft and it will draw the layout properly.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mylabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="4dp"
android:drawablePadding="8dp"
android:drawableLeft="#drawable/reminder"
android:lines="1"
android:textSize="24sp" >
</TextView>
I have a GridView arranged in a 3x4 matrix, each item in the GridView is a FrameLayout containing an ImageView and a Textview. Initially the TextViews are set to display the letter "X". When clicked on, the letter is changed to "Y".
It works on all the GridView items except the first one. If I click on the first one (top left) then nothing happens, no matter how long I wait. If I then click anywhere else on the Android emulator screen (even outside the GridView itself), at that point the top left GridView item changes to "Y".
I have a gut feeling it is something to do with the fact that "getView" in "ImageAdapter" is being called several times with "position=0" before the GridView is rendered, the sequence is as follows:
0
0
1
2
3
4
5
6
7
8
9
10
11
0
Now maybe that's just how Android works, I don't know, but it seems strange. If anyone can help me out I'd appreciate it so much.
UPDATE: it appears the problem is related to "MyView=convertView" in getView(), if I simply remove this and always create a new View (as if convertView is null always) then the problem no longer exists. Now I don't think this solution will be an issue as I don't use scrolling and the number of Views created should be 12 (i.e. a 3x4 GridView), but if anyone can explain the correct solution to the problem it would help a lot, thanks.
My main activity (and only activity):
package com.xxxxxx.test;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
init_gridview();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void init_gridview()
{
setContentView(R.layout.game);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setNumColumns(3);
gridview.setColumnWidth(32);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
grid_click(position,v);
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount()
{
return(3*4);
}
public Object getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View MyView = convertView;
if (convertView == null)
{
LayoutInflater li = getLayoutInflater();
MyView = li.inflate(R.layout.grid_item, null);
}
else
{
MyView=convertView;
}
TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text);
tv.setText("X");
ImageView iv = (ImageView)MyView.findViewById(R.id.grid_item_image);
iv.setImageResource(R.drawable.tile);
MyView.setLayoutParams(new GridView.LayoutParams(32,32));
return(MyView);
}
}
private void grid_click(int position, View v)
{
View clicked_view=v;
TextView tv2 = (TextView)clicked_view.findViewById(R.id.grid_item_text);
tv2.setText("Y");
}
}
The main layout, called game.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Layout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:gravity="center"
android:background="#android:color/white">
<GridView
android:id="#+id/gridview"
android:background="#android:color/white"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="106dp"
android:numColumns="auto_fit"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="none"
android:gravity="center"
android:listSelector="#android:color/transparent"
/>
</LinearLayout>
Finally the FrameLayout for each item in the GridView, called grid_item.xml:
<?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:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/grid_item_image"
android:src="#drawable/tile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="contentDescription"
/>
<TextView
android:id="#+id/grid_item_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textStyle="bold"
android:textSize="17sp"
android:shadowColor="#555555"
android:shadowDx="1.0"
android:shadowDy="1.0"
android:shadowRadius="1.5"
/>
</FrameLayout>
I think the problem is with your grid_click function it assumes that the view being clicked is the whole cell (FrameLayout) when it could possibly be just the image or text view itself.
I'm pretty new to Android and I have been playing about with GridView. I've got stuck trying to retrieve Strings from individual elements of the GridView so that I can save state based on the changes a user has made.
I've mocked up a stripped down version of what I'm trying to do for this question:
The view of each element in the grid is made up of a TextView and an EditText defined by the following xml file; grid_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "#+id/single_item_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id = "#+id/label"
android:layout_width = "fill_parent"
android:layout_height="wrap_content"
android:inputType="text">
</TextView>
<EditText
android:id = "#+id/item_value"
android:layout_width = "fill_parent"
android:layout_height="wrap_content"
android:inputType="text">
</EditText>
</LinearLayout>
My main.xml, consisting of a button and a gridview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/editbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRetrieveButtonClick"
android:text="#string/get" android:clickable="true"/>
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="250dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:paddingTop="50dp">
</GridView>
</LinearLayout>
My Activity Class:
package com.jdev.simplegrid;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;
public class SimpleGridActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
//Some hard-coded sample data -each person has a birth-name and a nickname
ArrayList<Person> people = new ArrayList<Person>();
people.add(new Person("David","Dave"));
people.add(new Person("Bruce","Batman"));
people.add(new Person("John","J"));
gridview.setAdapter(new SimpleAdapter(this, people));
}
public void onRetrieveButtonClick(View view)
{
Toast.makeText(getBaseContext(), "Get the String value of EditText at position 1 of the gridview e.g Batman", Toast.LENGTH_LONG).show();
//Get the String value of EditText at position 1 of the gridview. e.g Batman
}
}
And finally my Adapter for the view:
package com.jdev.simplegrid;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
public class SimpleAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Person> personList;
public SimpleAdapter(Context c, ArrayList<Person> people) {
mContext = c;
personList = people;
}
public int getCount() {
return personList.size();
}
public Person getItem(int position) {
return personList.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.grid_item, parent, false);
TextView birthnameLabel=(TextView)view.findViewById(R.id.birthname);
birthnameLabel.setText(personList.get(position).getBirthname());
EditText nicknameText=(EditText)view.findViewById(R.id.nickname);
nicknameText.setText(personList.get(position).getNickname());
return view;
}
}
So my question is, how do I retrieve the a value from the gridview on the click of a button. Say the value "Batman" in EditText at position 1 of the gridview.
I feel like I'm really missing something here!
gridview.getAdapter().getItem(1).getNickname();
Is that what you're looking for? assuming your Person object has a getter method for the nickname of course. - Sorry, obviously I could've seen that in your custom adapter.
If your the idea is the user can change the nickname in the EditText, you'll probably want to add a TextChangedListener (TextWatcher) to each of them and after editting update the nickname on the Person object associated with that position in the grid; e.g. with the help of a setNickname(String) method.
The easiest way to think about this is probably in terms of 'models' and 'views'. The TextViews and EditTexts are the views, whereas the Person objects in the adapter are the models. If you want to make any changes to the data, modify the underlying models with some logic and simply have the views update/refresh after that.