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!
Related
I'm trying to add a Firebase Recyclerview in my Android App. When I add, all the data is getting fetched from Firestore normally, but when it comes to handle onClick event, it is not working at all.
Things I followed:
Added Interface with method.
Implemented interface in my TipsActivity.java
Here is the code:
TipsActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Toast;
import android.util.Log;
import com.firebase.ui.firestore.paging.FirestorePagingOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class TipsActivity extends AppCompatActivity implements FirestoreTipsAdapter.OnListItemClick {
FirestoreTipsAdapter firestoreTipsAdapter;
FirebaseFirestore firebaseFirestore;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips);
firebaseFirestore = FirebaseFirestore.getInstance();
recyclerView = findViewById(R.id.list);
Query query = firebaseFirestore.collection("DailyTips").document("MyTips").collection("Tips");
PagedList.Config config = new PagedList.Config.Builder()
.setInitialLoadSizeHint(10)
.setPageSize(5)
.build();
FirestorePagingOptions<TipsModel> firestorePagingOptions = new FirestorePagingOptions.Builder<TipsModel>()
.setLifecycleOwner(this)
.setQuery(query,config,TipsModel.class)
.build();
firestoreTipsAdapter = new FirestoreTipsAdapter(firestorePagingOptions,this,this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(firestoreTipsAdapter);
}
#Override
public void onItemClick() {
Toast.makeText(this, "Show up bruh!", Toast.LENGTH_SHORT).show();
Log.d("AT_LEAST","You should work");
}
}
And here goes my:
FirestoreTipsAdapter.java
package com.mycompany.company;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.paging.FirestorePagingAdapter;
import com.firebase.ui.firestore.paging.FirestorePagingOptions;
public class FirestoreTipsAdapter extends FirestorePagingAdapter<TipsModel, FirestoreTipsAdapter.TipsViewHolder> {
private OnListItemClick onListItemClick;
Context context;
public FirestoreTipsAdapter(#NonNull FirestorePagingOptions<TipsModel> options,OnListItemClick onListItemClick,Context context) {
super(options);
this.onListItemClick = onListItemClick;
this.context = context;
}
#Override
protected void onBindViewHolder(#NonNull TipsViewHolder holder, int position, #NonNull TipsModel model) {
holder.title.setText(model.getTitle());
holder.description.setText(model.getDescription());
}
#NonNull
#Override
public TipsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new TipsViewHolder(view);
}
public class TipsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title,description;
public TipsViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.list_title);
description = itemView.findViewById(R.id.list_desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Are you working bro?", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClick(View v) {
onListItemClick.onItemClick();
}
}
public interface OnListItemClick{
void onItemClick();
}
}
Here is the code of list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
android:id="#+id/tipCardView"
app:cardElevation="5dp"
app:cardBackgroundColor="#E2E0EE"
app:cardCornerRadius="5dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="#+id/list_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:background="?attr/selectableItemBackground"
android:padding="16dp">
<TextView
android:id="#+id/list_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textColor="#android:color/black"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/list_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="Description" />
</LinearLayout>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/curveshape"
android:layout_gravity="end|bottom"
android:layout_marginBottom="-30dp"
android:alpha="0.2"
/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/tips"
android:layout_gravity="end|bottom"
android:layout_marginBottom="-10dp"
android:layout_marginRight="25dp"
android:alpha="0.2"
/>
</androidx.cardview.widget.CardView>
Note: I'm able to fetch data from Firestore, it is showing data properly.
Please help. I followed all other answers from Stack Overflow.
In the given setup, the OnClickListener is being set on the ViewHolder's itemView, which will be the root View in its layout, which is the CardView. However, the clickable and focusable attributes set on the LinearLayout cause it to get first grabs on touch events, so it's basically intercepting them before the CardView would handle them to respond to a click. There's no listener on the LinearLayout, though, so nothing happens.
Assuming that you want the entire item View clickable, simply remove the android:clickable="true" and android:focusable="true" attributes from the <LinearLayout>. With no clickable or focusable children, the CardView will then end up registering the click.
If instead you might want only a certain child clickable – e.g., the LinearLayout – then you would set the OnClickListener on that child, rather than the whole CardView. You still wouldn't need those attributes anywhere, though, if that's to be the only clickable child or grandchild. Those attributes usually aren't necessary in basic, relatively flat layouts, like that for your list items.
I know that there were a lot of questions like this one, but I haven't been able to find the answer I'm looking for...
I'd like to dynamically create some TextView in an already existing ScrollView. I've done something that I thought would have been okay, but the app stops when it comes to this fragment?
I can't put the whole project because the files are numerous, but here are the concerned .java and .xml:
NotesPageFragment.java
package com.a3m.Controllers.Fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.a3m.Controllers.ui.Controler;
import com.a3m.Controllers.core.Task;
import com.a3m.R;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class NotesPageFragment extends Fragment {
private Controler controler;
private ScrollView mScrollView;
public static NotesPageFragment newInstance() {
return(new NotesPageFragment());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_notes_page, container, false);
this.controler = Controler.getInstance();
this.mScrollView = v.findViewById(R.id.fragment_page_notes_scrollview);
//addNotes(notes,getAllTasks());
addNotes(v, getAllTasks());
return v;
}
public ArrayList<Task> getAllTasks()
{
/*
** ici le code qui se connecte à la bdd et retourne toutes les tasks disponibles
*/
ArrayList<Task> tasks = new ArrayList<>();
ArrayList<String> n =new ArrayList<>();
n.add("detail1");
n.add("detail2");
n.add("detail3");
Task t1=new Task(0,0,null,"t1",0,0,null,0,null,null,n,null);
Task t2=new Task(0,0,null,"t2",0,0,null,0,null,null,n,null);
Task t3=new Task(0,0,null,"t3",0,0,null,0,null,null,n,null);
Task t4=new Task(0,0,null,"t4",0,0,null,0,null,null,n,null);
Task t5=new Task(0,0,null,"t5",0,0,null,0,null,null,n,null);
Task t6=new Task(0,0,null,"t6",0,0,null,0,null,null,n,null);
Task t7=new Task(0,0,null,"t7",0,0,null,0,null,null,n,null);
tasks.add(t1);
tasks.add(t2);
tasks.add(t3);
tasks.add(t4);
tasks.add(t5);
tasks.add(t6);
tasks.add(t7);
return tasks;
}
public void addNotes(View view, ArrayList<Task> tasks) {
Iterator<Task> itr_tasks = tasks.iterator();
Task task;
String taskNote;
while(itr_tasks.hasNext()) {
taskNote = "";
task = itr_tasks.next();
taskNote += task.getName();
Iterator<String> itr_notes = task.getNotes().iterator();
while(itr_notes.hasNext()) {
taskNote += "\t\t\t" + itr_notes.next() + "\t\t\t";
}
final TextView taskNotes = new TextView(getActivity());
taskNotes.setText(taskNote);
mScrollView.addView(taskNotes);
}
}
}
fragment_notes_page.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:id="#+id/fragment_page_news_rootview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EDD9CF"
android:contentDescription="NotesPage"
android:gravity="center"
tools:context="com.a3m.Controllers.Fragments.NotesPageFragment">
<ScrollView
android:id="#+id/fragment_page_notes_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/nav_header_marginLeft">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="171dp"
android:src="#android:drawable/ic_menu_info_details" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="65dp"
android:text="Notes"
android:textAlignment="center"
android:textAllCaps="false"
android:textSize="30sp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
I'm aware that the IDs in the .xml aren't really good, but I'll improve them later...
If someone has an idea or can show me were the answer is, I'll gladly accept this help!!
ScrollView and all it's relatives that scroll the content (i.e. NestedScrollView) allow only for one child. You cannot add new views directly to ScrollView if it already has one child view.
Quote from java doc to ScrollView class:
/**
* A view group that allows the view hierarchy placed within it to be scrolled.
* Scroll view may have only one direct child placed within it.
* To add multiple views within the scroll view, make
* the direct child you add a view group, for example {#link LinearLayout}, and
* place additional views within that LinearLayout.
...
*/
And if you look inside of the class you will find that it overrides all addView methods:
To fix the issue what you need to do is to add id to your LinearLayout and insert new views into it.
I'd recommend changing it all to RecyclerView + Adapter.
Official tutorials from Google on how to use RecyclerView and Adapters
Actually, I was trying to implement a shopping cart using Android Studio. There is a custom list view in the main page included an "Add to Cart" button. So, whenever I click on the button the item must be added in the cart. But, I have no idea. Please guys, help me out. I'm a newbie.
Here is the Product Adapter
package com.example.raswap.octomatic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by aurora on 22/03/16.
*/
public class Pro_Adapter extends ArrayAdapter {
List list = new ArrayList();
public Pro_Adapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler{
ImageView img;
TextView p_name;
TextView b_name;
TextView price;
Button b_atc;
}
#Override
public void add(Object object) {
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.e_layout, parent, false);
handler = new DataHandler();
handler.img = (ImageView)row.findViewById(R.id.pro_image);
handler.p_name = (TextView)row.findViewById(R.id.pro_name);
handler.b_name = (TextView)row.findViewById(R.id.brand);
handler.price = (TextView)row.findViewById(R.id.pricing);
handler.b_atc = (Button)row.findViewById(R.id.atc);
row.setTag(handler);
}else{
handler = (DataHandler)row.getTag();
}
Product_data_provider dataProvider;
dataProvider = (Product_data_provider)this.getItem(position);
handler.img.setImageResource(dataProvider.getPro_img_resource());
handler.p_name.setText(dataProvider.getPro_name());
handler.b_name.setText(dataProvider.getBr_name());
handler.price.setText(dataProvider.getPricing());
return row;
}
}
Here is the Main Activity class:
package com.example.raswap.octomatic;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class E_shop extends Activity {
ListView listView;
int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
String[] pro_name;
String[] br_name;
String[] price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_e_shop);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
View z = findViewById(R.id.oct_logo);
z.setClickable(true);
z.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, MainActivity.class));
}
});
View x = findViewById(R.id.for_user_info);
x.setClickable(true);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, UserInformation.class));
}
});
Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
ListView listView = (ListView)findViewById(R.id.e_list);
listView.setAdapter(adapter);
pro_name = getResources().getStringArray(R.array.nameOfProduct);
br_name = getResources().getStringArray(R.array.branding);
price = getResources().getStringArray(R.array.pricing);
int i = 0;
for(String pro: pro_name){
Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
adapter.add(dataProvider);
i++;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
newActivity.putExtra("pro_emage",R.drawable.gb32);
newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
startActivity(newActivity);
break;
case 1:
Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
Activity1.putExtra("pro_emage",R.drawable.tb1);
Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
startActivity(Activity1);
break;
case 2:
Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
Activity2.putExtra("pro_emage", R.drawable.dvd);
Activity2.putExtra("title", "A pack of 50 DVD's");
Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
startActivity(Activity2);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
}
}
Here is the Product Data Provider Class:
package com.example.raswap.octomatic;
/**
* Created by aurora on 22/03/16.
*/
public class Product_data_provider {
private int pro_img_resource;
private String pro_name;
private String br_name;
private String pricing;
public int getPro_img_resource() {
return pro_img_resource;
}
public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
this.setPro_img_resource(pro_img_resource);
this.setPro_name(pro_name);
this.setBr_name(br_name);
this.setPricing(pricing);
}
public void setPro_img_resource(int pro_img_resource) {
this.pro_img_resource = pro_img_resource;
}
public String getPro_name() {
return pro_name;
}
public void setPro_name(String pro_name) {
this.pro_name = pro_name;
}
public String getBr_name() {
return br_name;
}
public void setBr_name(String br_name) {
this.br_name = br_name;
}
public String getPricing() {
return pricing;
}
public void setPricing(String pricing) {
this.pricing = pricing;
}
}
Now, Custom ListView XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/pro_image"
android:src="#drawable/gb32"
android:layout_width="160dp"
android:layout_height="match_parent" />
<LinearLayout
android:background="#afeeee"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Product Name"
android:id="#+id/pro_name"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Branding"
android:id="#+id/brand"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:textColor="#000"
android:id="#+id/pricing"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:id="#+id/atc" />
</LinearLayout>
</LinearLayout>
<View
android:layout_below="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>
</RelativeLayout>
</RelativeLayout>
and finally the main layout XML file:
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.raswap.octomatic.E_shop">
<ListView
android:id="#+id/e_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Add your button's OnClick event in the Pro_Adapter's getView() methond as you do normally in your activities' onCreate() method.
Implement OnClickListener in your adapter class and get the Button click first and do the other task when you get the event. If you need the call back to your main activity class implement your own listener.follow the link enter link description here
Add the onClickListener to your Button in getView() of your ListAdapter.
If you want handle event click button in row, i'm think you should answer set button onclick event for every row of listview
you can try this.
Change in custom Listview xml file.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:onClick="AddCart"
android:id="#+id/atc" />
In MainActivity
public void AddCart(View v)
{
LinearLayout vwParentRow = (LinearLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
child.setText("I've been clicked!");
vwParentRow.refreshDrawableState();
}
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.
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.