Im rendering a android layout.xml file on react native.while trying to implement events on views inside layout.xml on android.I'm not able to acheive it
my customview.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='40dp'
android:orientation="horizontal"
>
<TextView android:id="#+id/multipleCameraText"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Text View from Native"
/>
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:height="40dp"
android:layout_height="wrap_content"
android:text="Button 1"
/>
<Button android:id="#+id/button2"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:height="40dp"
android:text="Button 2"
/>
</LinearLayout>
my customview.java
package com.typesproject;
import android.content.Context;
import android.widget.LinearLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
public class CustomView2 extends LinearLayout {
private Context context;
public CustomView2(Context context) {
super(context);
this.context=context;
this.init();
}
public void init() {
//modified here.
inflate(context, R.layout.customview2, this);
}
public void onReceiveNativeEvent() {
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"topChange",
event);
}
}
I want to implement button clicks on two buttons(button1 and button2) and change text inside text view(multipleCameraText).
my customViewManager.java
package com.typesproject;
import android.view.View;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.image.ReactImageView;
import javax.annotation.Nonnull;
public class CustomViewManager extends SimpleViewManager<CustomView> {
public static final String Custom_View="CustomView";
#Nonnull
#Override
public String getName() {
return Custom_View;
}
#Nonnull
#Override
protected CustomView createViewInstance(#Nonnull ThemedReactContext reactContext) {
return new CustomView(reactContext);
}
}
Please let me know how we can achieve separate events for buttons and textview.
the layout view can not use in this situation. you have to define a class for the view, then use it in the ViewManager.
As for your situation, you firstly could define a class which extends Button,
public class CustomButton extends Button {}
then in the CustomViewManager expose the props and event
#ReactProp(name = "text")
public void setContenxt(CustomButton button, #Nullable String text) {
view.setSource(sources);
}
#ReactProp(name = "text")
public void setContenxt(CustomButton button, #Nullable String text) {
button.setText(sources);
}
as for the event, you can read official API.
If you want to define a view that shows like the layout XML. the view have to extend Linearlayou or ViewGroup. that effect realizes is complex. the related
knowledge is the android custom view. you may have to override onDraw, onMeasure, onLayout.
you can look at the ReactViewGroup class, it will give you some clues
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 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!
I am trying to customise an EditTextPreference to display a textview(i.e to display value of the preference) and a clear/delete button on its right side.
I created CustomEditTextPreference.java
package com.customedittextpreference;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.Image;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
/**
* Created by cyong on 23/04/16.
*/
public class CustomEditTextPreference extends EditTextPreference {
private ImageButton clearButton;
private TextView valueTextView;
public CustomEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupChangeListener();
}
public CustomEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setupChangeListener();
}
public CustomEditTextPreference(Context context) {
super(context);
setupChangeListener();
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
valueTextView = (TextView) view.findViewById(R.id.value_textview);
clearButton = (ImageButton) view.findViewById(R.id.clear_button);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText("");
}
});
String valueString = getText();
Log.v(Settings.APP_NAME, "refreshValue(): valueString=" + valueString);
valueTextView.setText(valueString);
toggleClearButton(valueString);
}
private void toggleClearButton(String value)
{
if (value.length()==0)
{
clearButton.setVisibility(View.GONE);
}
else
{
clearButton.setVisibility(View.VISIBLE);
}
}
private void setupChangeListener()
{
setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newStringValue = (String) newValue;
valueTextView.setText(newStringValue);
toggleClearButton(newStringValue);
return true;
}
});
}
}
CustomEditTextPreference class use the layout below(i.e prefwidget_edittext.xml) as widget layout
<?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="horizontal"
android:descendantFocusability="blocksDescendants"
android:padding="0dp">
<TextView
android:id="#+id/value_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_gravity="center_vertical"
android:singleLine="true" />
<ImageButton
android:id="#+id/clear_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:layout_marginRight="5dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:layout_gravity="center_vertical"
android:src="#mipmap/delete_icon"
android:background="#00000000"
/>
</LinearLayout>
I specify my custom EditTextPreference in a preferences_list.xml under res/xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="status_choice"
android:entries="#array/array_status_entries"
android:entryValues="#array/array_status_values"
android:title="#string/choose_status_title"
android:summary="%s"
android:defaultValue="0"
/>
<CheckBoxPreference
android:defaultValue="false"
android:key="has_email"
android:title="#string/has_email_title" >
</CheckBoxPreference>
<com.customedittextpreference.CustomEditTextPreference
android:widgetLayout="#layout/prefwidget_edittext"
android:title="#string/productcode_title"
android:key="code"/>
</PreferenceScreen>
I can click on the edittextpreference and enter a string. The string entered would be saved, but would not display in textview of my custom widget layout after that. However, if I kill my app, and start it again, the textview would display the saved string. Now, when I click on the clear/delete button, I can see the value being deleted in but, the UI is not being updated to clear the string the textview and hide the clear/delete button.
For convenience, I have uploaded my sample project into github below:
Sample GitHub Project
Seems like notifyChanged() needs to be called when updating a Preference.
I noticed calls setTitle() and setSummary() would update the UI. It turns out, notifyChanged() is called in those both those functions.
Update the github project with the fix.
GitHub Project
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'm trying to use Android Annotations and dynamically add layout components when my createNewRow button is clicked. The app runs and displays the default rows defined in activity_main.xml and, after clicking createNewButton I see children attached to my dynamicTable in the debugger but the new children are not displayed. Here is my main activity XML:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/inflateLayout"
android:orientation="vertical"
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="net.richardriley.inflate.app.MainActivity">
<Button
android:id="#+id/createNewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/newRowButton"/>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/dynamicTable">
<TableRow>
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
</LinearLayout>
So simply a linear layout with a button and then a table container. Clicking createNewRow should add a new InflatedRow. Here is the XML for the row I want to dynamically add:
inflatedrow.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="#+id/inflatedRowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/inflatedRowLabel"/>
<Button
android:id="#+id/inflatedRowButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/defaultNewRowText"
/>
</merge>
Using AA my subclass for a tableRow is
InflatedRow.java
package net.richardriley.inflate.app;
import android.content.Context;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
/**
* inflate : Created by rgr on 20/03/14.
*/
#EViewGroup(R.layout.inflatedrow)
public class InflatedRow extends TableRow {
#ViewById
Button inflatedRowButton;
#ViewById
TextView inflatedRowTextView;
public InflatedRow(Context context) {
super(context);
}
}
and finally my main activity java itself:
MainActivity.java
package net.richardriley.inflate.app;
import android.support.v7.app.ActionBarActivity;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import org.androidannotations.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static ch.qos.logback.classic.android.BasicLogcatConfigurator.configureDefaultContext;
#OptionsMenu(R.menu.main)
#EActivity(R.layout.activity_main)
public class MainActivity extends ActionBarActivity {
static {
configureDefaultContext();
log = LoggerFactory.getLogger(MainActivity.class);
}
#ViewById
LinearLayout inflateLayout;
#ViewById
TableLayout dynamicTable;
public MainActivity() {
}
protected static Logger log;
#Click
void createNewRow() {
log.info("clicked");
InflatedRow_ inflatedRow=new InflatedRow_(this);
dynamicTable.addView(inflatedRow,0);
/*LayoutInflater layoutInflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.inflatedrow,null);
dynamicTable.addView(view);*/
}
#OptionsItem
void openSettingsSelected(){
log.info("Hello");
}
}
In createNewRow if I use the inflater service directly it works.
What am I missing?
many thanks.
Don't use the annotated class when you're inflating the view and make sure you're calling the build method that inflates it.
#Click
void createNewRow() {
log.info("clicked");
InflatedRow inflatedRow = new InflatedRow_.build(this);
dynamicTable.addView(inflatedRow,0);
}
instead of 'View inflatedRow= new InflatedRow_(this);' I use 'View inflatedRow=InflatedRow_.build(this);'. This is documented for custom controls and I needed to do it for a merged control group too. So mea culpa to a degree!
#Click
void createNewRow() {
log.info("clicked");
InflatedRow_ inflatedRow=InflatedRow_.build(this);
dynamicTable.addView(inflatedRow,0);
}
Alternatively (and no idea if this would continue to be supported:
#Click
void createNewRow() {
log.info("clicked");
/*View inflatedRow = InflatedRow_.build(this);*/
InflatedRow_ inflatedRow = new InflatedRow_(this);
inflatedRow.onFinishInflate();
dynamicTable.addView(inflatedRow, 0);
}