Pass reference of view to CustomView - android

I have one linear layout in that I have two views for an email address, one is Textview and another one is Edittext.
When there is empty or not proper email address then Textview's color should change to red,
if the user gets focus on edit text Textview's color should change to blue.
if the user lost focus on EditText then TextView's color should change to black.
To check how to achieve with customview, I have created a custom view of its parent view which is LinearLayout which is below
CustomLinearLayout.java file
public class CustomLinearLayout extends LinearLayout {
int editTextResourceId, textViewResourceId;
EditText editText;
TextView textView;
Context mContext;
public CustomLinearLayout(Context context) {
super(context);
mContext = context;
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
inflate(context, R.layout.activity_register_account_new, this);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyleAttr, 0);
editTextResourceId = a.getResourceId(R.styleable.MyTextView_supportedEditText, NO_ID);
textViewResourceId = a.getResourceId(R.styleable.MyTextView_supportedTextView, NO_ID);
a.recycle();
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
if (editTextResourceId != 0 && textViewResourceId != 0) {
editText = (EditText)findViewById(editTextResourceId);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() != 0){
textView.setText(s);
}
}
});
}
}
}
activity_main.xml file looks like
<?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:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey"
android:orientation="vertical">
<mobile.android.view.CustomLinearLayout
style="#style/RegisterItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:supportedEditText="#id/edUserName"
custom:supportedTextView="#id/tvUserName"
android:orientation="horizontal">
<TextView
android:id="#+id/tvUserName"
style="#style/RegisterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/username" />
<EditText
android:id="#+id/edUserName"
style="#style/RegisterEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hint_username"
android:inputType="textPersonName" />
</mobile.android.view.CustomLinearLayout>
attris.xml file
<declare-styleable name="MyTextView">
<attr name="supportedEditText" />
<attr name="supportedTextView" />
</declare-styleable>
But whenever I debug code, it shows me 0 (resource id) instead of proper id or NO_ID.
Can anyone help me how to resolve this? thanks,

Try this code inside CustomLinearLayout.java :
private EditText findEditText() {
int i = 0;
for (; i < getChildCount(); i++) {
if (getChildAt(i) instanceof EditText) {
return (EditText) getChildAt(i);
}
}
return null;
}
private TextView findTextView() {
int i = 0;
for (; i < getChildCount(); i++) {
if (getChildAt(i) instanceof TextView) {
return (TextView) getChildAt(i);
}
}
return null;
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
TextView textView = findTextView();
EditText editText = findEditText();
if (editText != null) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
if (textView != null) {
textView.setText(s);
}
}
}
});
}
}

I built one thing like you want and I call it : EditTextComponent
This is java source code for EditTextComponent:
public class EdittextComponent extends InputComponent {
protected TextView tvTitle;
protected EditText edtInput;
protected int mInputType = InputType.TYPE_CLASS_TEXT;
protected int mMaxLine = 1;
protected InputFilter[] mInputFilter;
protected boolean hasFirstChange = false;
protected TextView tvWarning;
protected int mIDLayout = R.layout.component_edittext;
protected boolean isAlwaysShowWarning = false;
#Override
public View createView() {
LayoutInflater inflater = LayoutInflater.from(mContext);
rootView = inflater.inflate(mIDLayout, null, false);
tvTitle = rootView.findViewById(R.id.tv_title);
if (Utils.validateString(mTitle)) {
tvTitle.setText(mTitle);
}
edtInput = rootView.findViewById(R.id.edt_input);
if (Utils.validateString(mPlaceHolder)) {
edtInput.setHint(mPlaceHolder);
}
edtInput.setInputType(mInputType);
edtInput.setMaxLines(mMaxLine);
if (null != mInputFilter && mInputFilter.length > 0) {
edtInput.setFilters(mInputFilter);
}
if (Utils.validateString(mValue)) {
edtInput.setText(mValue);
}
if(null != mValueSelected){
isCompleted = true;
String value = (String) mValueSelected;
if(Utils.validateString(value)) {
edtInput.setText(value);
}
}
edtInput.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (null != s) {
hasFirstChange = true;
checkChange(s.toString().trim());
}
}
});
tvWarning = rootView.findViewById(R.id.tv_warning);
return rootView;
}
protected void checkChange(String source) {
if (null != mValidator) {
boolean newState = mValidator.validate(source);
if (isCompleted != newState) {
notifyStateChanged(newState, source);
}
} else {
if (source.length() == 0) {
if (isCompleted) {
notifyStateChanged(false, source);
}
} else if (!isCompleted) {
notifyStateChanged(true, source);
}
}
if(isCompleted){
edtInput.setBackgroundResource(R.drawable.bg_input);
tvWarning.setVisibility(View.INVISIBLE);
}
else{
showWarning(true);
}
}
protected void notifyStateChanged(boolean is_complete, String source) {
isCompleted = is_complete;
if (null != mCallBack) {
mCallBack.onChanged(isCompleted, source);
}
}
public void updateValue(String value){
mValue = value;
if(null != edtInput){
edtInput.setText(value);
}
checkChange(value);
}
#Override
public boolean validate() {
if(!isVisible){
return true;
}
if (!isCompleted ) {
showWarning(false);
}
return isCompleted;
}
protected void showWarning(boolean isCallByItSelf) {
String message = "Cannot be empty";
if (null != mValidator) {
message = mValidator.getMessage();
}
if(null != tvWarning) {
tvWarning.setText(message);
tvWarning.setVisibility(View.VISIBLE);
}
if(null != edtInput) {
edtInput.setBackgroundResource(R.drawable.bg_input_warning);
}
}
#Override
public String getValue() {
mValue = edtInput.getText().toString();
return mValue;
}
#Override
public Object getData() {
return getValue();
}
public void setInputType(int inputType) {
mInputType = inputType;
}
public void setMaxLine(int maxLine) {
mMaxLine = maxLine;
}
public void setInputFilter(InputFilter[] inputFilter) {
mInputFilter = inputFilter;
}
public void setIDLayout(int IDLayout) {
mIDLayout = IDLayout;
}
public void setAlwaysShowWarning(boolean alwaysShowWarning) {
isAlwaysShowWarning = alwaysShowWarning;
}}
And here is component_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:text="Last name"
android:textColor="#333333"
android:textSize="14sp"/>
<EditText
android:id="#+id/edt_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_title"
android:layout_marginStart="10dp"
android:layout_marginTop="9dp"
android:layout_marginEnd="10dp"
android:background="#drawable/bg_input_inactive"
android:paddingStart="19dp"
android:paddingTop="16dp"
android:paddingBottom="15dp"
android:textColor="#333333"
android:textSize="14sp"/>
<TextView
android:id="#+id/tv_warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edt_input"
android:layout_alignParentEnd="true"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:text="Cannot be empty"
android:textColor="#DD4033"
android:textSize="12sp"
android:visibility="invisible"/>
</RelativeLayout>
InputComponent.java
public class InputComponent extends BaseComponent {
protected String mTitle;
protected String mValue;
protected String mKey;
protected String mPlaceHolder;
protected Validator mValidator;
protected boolean isCompleted = false;
protected InputCallBack mCallBack;
protected float mWeight = 1;
public boolean validate(){
return false;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public String getValue() {
return mValue;
}
public void setValue(String value) {
mValue = value;
}
public String getKey() {
return mKey;
}
public void setKey(String key) {
mKey = key;
}
public void setCallBack(InputCallBack callBack) {
mCallBack = callBack;
}
public void setPlaceHolder(String placeHolder) {
mPlaceHolder = placeHolder;
}
public void setValidator(Validator validator) {
mValidator = validator;
}
public float getWeight() {
return mWeight;
}
public void setWeight(float weight) {
mWeight = weight;
}
}
BaseComponet.java
public class BaseComponent implements Comparable<BaseComponent>{
protected View rootView;
protected String mIDComponent;
protected Context mContext;
protected Object mValueSelected;
protected int mPosition;
protected boolean isVisible = true;
public BaseComponent() {
mContext = Manager.getInstance().getCurrentActivity();
}
public View createView() {
return rootView;
}
public Object getValueSelected() {
return mValueSelected;
}
public void setValueSelected(Object valueSelected) {
mValueSelected = valueSelected;
}
public String getIDComponent() {
return mIDComponent;
}
public void setIDComponent(String IDComponent) {
mIDComponent = IDComponent;
}
public void setRootView(View rootView) {
this.rootView = rootView;
}
public int getPosition() {
return mPosition;
}
public void setPosition(int position) {
mPosition = position;
}
public Object getData(){
return null;
}
public void removeAllView(){
}
public boolean isVisible() {
return isVisible;
}
public void setVisible(boolean visible) {
isVisible = visible;
}
public void updateView(){
if(null != rootView){
if(isVisible){
rootView.setVisibility(View.VISIBLE);
}
else{
rootView.setVisibility(View.GONE);
}
}
}
public View getRootView() {
return rootView;
}
#Override
public int compareTo( BaseComponent otherComponent) {
if (null != otherComponent) {
return (otherComponent.getPosition() - getPosition());
}
return 0;
}
}
And this is how you can use EditTextComponent:
EdittextComponent lastNameComponent = new EdittextComponent();
lastNameComponent.setPlaceHolder("Enter last name");
lastNameComponent.setTitle("Last name");
lastNameComponent.setKey("lastname");
lastNameComponent.setCallBack(new InputCallBack() {
#Override
public void onChanged(boolean isSelected, Object data) {
checkComplete();
}
});
listInputComponents.add(lastNameComponent);
You can use this component to create email, last name, phonecode .... and add them to listInputComponents ( an array)
Then you can add them to a linearlaylout like this:
LinearLayout llBody = findViewById(...)
for(BaseComponent component: listInputComponents)
{ llBody.addView(component.createView()
}

Related

Android AutoCompeleteTextView not gives proper result

I am new in android and use Custom AutoCompleteTextView, here is code form AutoCompleteText
<com.xxxxxxxx.supports.CustomAutoComplete
android:id="#+id/edit_search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:completionThreshold="3"
android:ellipsize="end"
android:fontFamily="#font/roboto"
android:gravity="center_vertical"
android:hint="#string/search_products_colors_more"
android:imeActionId="123456"
android:imeOptions="actionSearch"
android:inputType="textCapWords"
android:paddingLeft="10dp"
android:textColor="#color/dark_text_color"
android:textColorHint="#color/light_text_color"
android:textSize="#dimen/font_14sp" />
This is list comes when I search some thing over server
and When I clicked on first item Steel Grey It shows like this.
I am not able to figure out the error, Sometime it comes and sometime not.
Please help.
Edit Update:
public class CustomAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {
private static final int MESSAGE_TEXT_CHANGED = 100;
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
private ProgressBar mLoadingIndicator;
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
CustomAutoComplete.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
public CustomAutoComplete(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLoadingIndicator(ProgressBar progressBar) {
mLoadingIndicator = progressBar;
}
public void setAutoCompleteDelay(int autoCompleteDelay) {
mAutoCompleteDelay = autoCompleteDelay;
}
#Override
protected void performFiltering(CharSequence text, int keyCode) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.VISIBLE);
}
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
}
#Override
public void onFilterComplete(int count) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.GONE);
}
super.onFilterComplete(count);
}
}
Model Class below here
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}}
Code in fragment class
public CustomAutoComplete edit_search;
edit_search.setThreshold(3);
edit_search.setAdapter(new SearchAdapter(getActivity(), resultList, SearchItems.this)); // 'this' is Activity instance
edit_search.setLoadingIndicator(progress_search);
edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
try {
getPerspective().closeKeyboard();
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (resultList.size() != 0) {
if (edit_search.getText().length() > 2) {
String text = resultList.get(0).getSuggetions();
Log.e(TAG, "Text : " + text);
if (text.equalsIgnoreCase("No Results!")) {
edit_search.dismissDropDown();
layout_no_result.setVisibility(View.VISIBLE);
layout_mic.setVisibility(View.GONE);
} else {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
getPerspective().openProdcuctList("0", text.trim());
}
} else if (edit_search.getText().length() < 3 && edit_search.getText().length() > 0) {
getPerspective().showMessage("Enter minimum three characters!");
} else if (edit_search.getText().length() <= 0) {
getPerspective().showMessage("Please enter your search query!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
edit_search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (edit_search.getText().length() == 0) {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Now Adapter class code is
public class SearchAdapter extends BaseAdapter implements Filterable {
public Context context;
private List<SearchResults> resultsList;
SearchItems searchItems;
Perspective perspective;
private LayoutInflater inflater;
public Perspective getPerspective() {
if (perspective == null)
perspective = (Perspective) context;
return perspective;
}
public SearchAdapter(Context context, List<SearchResults> resultsList, SearchItems searchItems) {
this.context = context;
this.resultsList = resultsList;
this.searchItems = searchItems;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultsList.size();
}
#Override
public Object getItem(int position) {
return resultsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_search_result_row, parent, false);
viewHolder.txt_item_name = (TextView) convertView.findViewById(R.id.txt_item_name);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_item_name.setText(resultsList.get(position).getSuggetions());
viewHolder.txt_item_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String query = resultsList.get(position).getSuggetions();
Log.e("Search","Query : "+query);
// searchItems.edit_search.setText(query);
if (!query.equals("No Results!")) {
getPerspective().closeKeyboard();
searchItems.edit_search.dismissDropDown();
getPerspective().openProdcuctList("0", query);
}
}
});
return convertView;
}
class ViewHolder {
TextView txt_item_name;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<SearchResults> listSuggs = findSuggastions(context, constraint.toString());
filterResults.values = listSuggs;
filterResults.count = listSuggs.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultsList = (List<SearchResults>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
private List<SearchResults> findSuggastions(Context context, String title) {
resultsList.clear();
return resultsList = getSearchResults(title);
}
private List<SearchResults> getSearchResults(final String keyword) {
String tag_string_req = "req_top_search";
StringRequest strReq = new StringRequest(Request.Method.POST,
APIs.url_api_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("SearchAdapter", "Response : " + response);
JSONArray object = new JSONArray(response);
//resultsList.clear();
for (int i = 0; i < object.length(); i++) {
JSONObject jsonObject = object.getJSONObject(i);
String prod_id = jsonObject.getString("product_id");
String prod_nam = jsonObject.getString("name");
SearchResults searchSuggs = new SearchResults(prod_nam, prod_id);
resultsList.add(searchSuggs);
}
if (resultsList.size() == 1) {
String prod_nam = resultsList.get(0).getSuggetions();
if (prod_nam.equalsIgnoreCase("No Results!")) {
searchItems.edit_search.dismissDropDown();
searchItems.layout_no_result.setVisibility(View.VISIBLE);
searchItems.layout_mic.setVisibility(View.GONE);
} else {
searchItems.layout_no_result.setVisibility(View.GONE);
searchItems.layout_mic.setVisibility(View.VISIBLE);
}
}else {
getPerspective().closeKeyboard();
}
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("keyword", keyword);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
Controller.getInstance().addToRequestQueue(strReq, tag_string_req);
return resultsList;
}
}
I have updated code,
Just Override toString methods and return data that you want to display.
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}
#Override
public final String toString()
{
return suggetions;
}
}

Two way binding on custom view

I have a componed view in android contains several textViews and one EditText. I defined an attribute for my custom view called text and getText, setText methods. Now I want to add a 2-way data binding for my custom view in a way its bind to inner edit text so if my data gets updated edit text should be updated as well (that's works now) and when my edit text gets updated my data should be updated as well.
My binding class looks like this
#InverseBindingMethods({
#InverseBindingMethod(type = ErrorInputLayout.class, attribute = "text"),
})
public class ErrorInputBinding {
#BindingAdapter(value = "text")
public static void setListener(ErrorInputLayout errorInputLayout, final InverseBindingListener textAttrChanged) {
if (textAttrChanged != null) {
errorInputLayout.getInputET().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
textAttrChanged.onChange();
}
});
}
}
}
I tried to bind text with the code below. userInfo is an observable class.
<ir.avalinejad.pasargadinsurance.component.ErrorInputLayout
android:id="#+id/one_first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="#string/first_name"
app:text="#={vm.userInfo.firstName}"
/>
When I run the project I get this error
Error:(20, 13) Could not find event 'textAttrChanged' on View type 'ir.avalinejad.pasargadinsurance.component.ErrorInputLayout'
And my custom view looks like this
public class ErrorInputLayout extends LinearLayoutCompat implements TextWatcher {
protected EditText inputET;
protected TextView errorTV;
protected TextView titleTV;
protected TextView descriptionTV;
private int defaultGravity;
private String title;
private String description;
private String hint;
private int inputType = -1;
private int lines;
private String text;
private Subject<Boolean> isValidObservable = PublishSubject.create();
private Map<Validation, String> validationMap;
public ErrorInputLayout(Context context) {
super(context);
init();
}
public ErrorInputLayout(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
readAttrs(attrs);
init();
}
public ErrorInputLayout(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
readAttrs(attrs);
init();
}
private void readAttrs(AttributeSet attrs){
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs,
R.styleable.ErrorInputLayout,
0, 0);
try {
title = a.getString(R.styleable.ErrorInputLayout_title);
description = a.getString(R.styleable.ErrorInputLayout_description);
hint = a.getString(R.styleable.ErrorInputLayout_hint);
inputType = a.getInt(R.styleable.ErrorInputLayout_android_inputType, -1);
lines = a.getInt(R.styleable.ErrorInputLayout_android_lines, 1);
text = a.getString(R.styleable.ErrorInputLayout_text);
} finally {
a.recycle();
}
}
private void init(){
validationMap = new HashMap<>();
setOrientation(VERTICAL);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
titleTV = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_default_title_textview, null, false);
addView(titleTV);
descriptionTV = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_default_description_textview, null, false);
addView(descriptionTV);
readInputFromLayout();
if(inputET == null) {
inputET = (EditText) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_defult_edittext, this, false);
addView(inputET);
}
errorTV = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_default_error_textview, null, false);
addView(errorTV);
inputET.addTextChangedListener(this);
defaultGravity = inputET.getGravity();
//set values
titleTV.setText(title);
if(description != null && !description.trim().isEmpty()){
descriptionTV.setVisibility(VISIBLE);
descriptionTV.setText(description);
}
if(inputType != -1)
inputET.setInputType(inputType);
if(hint != null)
inputET.setHint(hint);
else
inputET.setHint(title);
inputET.setLines(lines);
inputET.setText(text);
}
private void readInputFromLayout() {
if(getChildCount() > 3){
throw new IllegalStateException("Only one or zero view is allow in layout");
}
if(getChildCount() == 3){
View view = getChildAt(2);
if(view instanceof EditText)
inputET = (EditText) view;
else
throw new IllegalStateException("only EditText is allow as child view");
}
}
public void setText(String text){
inputET.setText(text);
}
public String getText() {
return text;
}
public void addValidation(#NonNull Validation validation, #StringRes int errorResourceId){
addValidation(validation, getContext().getString(errorResourceId));
}
public void addValidation(#NonNull Validation validation, #NonNull String error){
if(!validationMap.containsKey(validation))
validationMap.put(validation, error);
}
public void remoteValidation(#NonNull Validation validation){
if(validationMap.containsKey(validation))
validationMap.remove(validation);
}
public EditText getInputET() {
return inputET;
}
public TextView getErrorTV() {
return errorTV;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
checkValidity();
if(editable.toString().length() == 0) //if hint
inputET.setGravity(Gravity.RIGHT);
else
inputET.setGravity(defaultGravity);
}
public Subject<Boolean> getIsValidObservable() {
return isValidObservable;
}
private void checkValidity(){
//this function only shows the first matched error.
errorTV.setVisibility(INVISIBLE);
for(Validation validation: validationMap.keySet()){
if(!validation.isValid(inputET.getText().toString())) {
errorTV.setText(validationMap.get(validation));
errorTV.setVisibility(VISIBLE);
isValidObservable.onNext(false);
return;
}
}
isValidObservable.onNext(true);
}
}
After hours of debugging, I found the solution. I changed my Binding class like this.
#InverseBindingMethods({
#InverseBindingMethod(type = ErrorInputLayout.class, attribute = "text"),
})
public class ErrorInputBinding {
#BindingAdapter(value = "textAttrChanged")
public static void setListener(ErrorInputLayout errorInputLayout, final InverseBindingListener textAttrChanged) {
if (textAttrChanged != null) {
errorInputLayout.getInputET().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
textAttrChanged.onChange();
}
});
}
}
#BindingAdapter("text")
public static void setText(ErrorInputLayout view, String value) {
if(value != null && !value.equals(view.getText()))
view.setText(value);
}
#InverseBindingAdapter(attribute = "text")
public static String getText(ErrorInputLayout errorInputLayout) {
return errorInputLayout.getText();
}
First, I added AttrChanged after the text like this #BindingAdapter(value = "textAttrChanged") which is the default name for the listener and then I added getter and setter methods here as well.
event = "android:textAttrChanged" works for me:
object DataBindingUtil {
#BindingAdapter("emptyIfZeroText") //replace "android:text" on EditText
#JvmStatic
fun setText(editText: EditText, text: String?) {
if (text == "0" || text == "0.0") editText.setText("") else editText.setText(text)
}
#InverseBindingAdapter(attribute = "emptyIfZeroText", event = "android:textAttrChanged")
#JvmStatic
fun getText(editText: EditText): String {
return editText.text.toString()
}
}
you need add one more function
#BindingAdapter("app:textAttrChanged")
fun ErrorInputLayout.bindTextAttrChanged(listener: InverseBindingListener) {
}

clicking on calendar icon in the editext for the first time is not showing the datepicker dialog

Hai I have editext in my app where we can set the date of birth. in that editext I have a calendar icon. If we click on calendar icon it should open the datepicker dialog. But in my case if I click on calendar icon it is showing paste, clicpboard, selectall options in my editext instead of showing the date picker dialog and if we click on the calendar icon again for the second time it is opening the date picker dialog. How to make the datepicker dialog open for the first click on my calendar icon. I alreadt set setFocusable and setFocusableInTouchMode to false but no use. please help to fix the same.
This is the fragment where I am having edittext for date of birth:
public class RegistrationBasicInformationFragment extends Fragment implements
IRegistrationBasicInformationView, IRegistrationItemEventListener, View.OnFocusChangeListener {
private TextView mRegistrationEnterYourBasicInformationLabel;
private RelativeLayout mRegistrationBasicInformationMainLayout;
private DsmApplication mDsmApplication;
private RegistrationItemView mRegistrationBasicInformationItemForFirstName;
private RegistrationItemView mRegistrationBasicInformationItemForLastName;
private RegistrationItemView mRegistrationBasicInformationItemForDob;
private RegistrationItemView mRegistrationBasicInformationItemForEmail;
private RegistrationItemView mRegistrationBasicInformationItemForGender;
private RegistrationItemView mRegistrationBasicInformationItemForNickName;
private RegistrationItemView mRegistrationBasicInformationItemForPhoneNumber;
private RegistrationItemView mRegistrationBasicInformationItemForPractice;
private RegistrationItemView mRegistrationBasicInformationItemForProvider;
private RegistrationBasicInformationController mRegistrationBasicInformationController;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.registration_basicinformation_view_v222, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDsmApplication = (DsmApplication) getActivity().getApplication();
loadController();
loadView(view);
}
private void loadController() {
mRegistrationBasicInformationController = new RegistrationBasicInformationController(this);
mDsmApplication.registerController(RegistrationBasicInformationController.TAG, mRegistrationBasicInformationController);
}
private void loadView(View view) {
mRegistrationBasicInformationMainLayout = (RelativeLayout) view
.findViewById(R.id.registration_basicinformation_relativelayout_for_itself);
mRegistrationEnterYourBasicInformationLabel = (TextView) view
.findViewById(R.id.registration_basicinformation_textview_for_headerlabel);
mRegistrationBasicInformationItemForFirstName = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_firstname);
mRegistrationBasicInformationItemForFirstName.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForLastName = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_lastname);
mRegistrationBasicInformationItemForLastName.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForDob = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_dob);
mRegistrationBasicInformationItemForGender = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_gender);
mRegistrationBasicInformationItemForPhoneNumber = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_phonenumber);
mRegistrationBasicInformationItemForPhoneNumber.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForNickName = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_nickname);
mRegistrationBasicInformationItemForNickName.mRegistrationItemTextTypeEditText
.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForNickName.mRegistrationItemTextTypeEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_NEXT) {
if (mRegistrationBasicInformationItemForDob.isEnabled() ) {
mRegistrationBasicInformationController.OnCalendarDateTimeIconClicked();
ViewUtils.hideVirturalKeyboard((EditText) textView);
} else {
mRegistrationBasicInformationItemForPhoneNumber.mRegistrationItemTextTypeEditText.requestFocus();
ViewUtils.showVirturalKeyboard(getActivity().getApplicationContext());
}
return true;
}
return false;
}
});
mRegistrationBasicInformationItemForEmail = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_email);
mRegistrationBasicInformationItemForEmail.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForPractice = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_practice);
mRegistrationBasicInformationItemForProvider = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_provider);
}
#Override
public void SetEnterYourBasicInformationLabel(String label) {
mRegistrationEnterYourBasicInformationLabel.setText(label);
}
#Override
public IRegistrationItemView CreateFirstNameItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForFirstName.SetEventListener(this);
mRegistrationBasicInformationItemForFirstName.SetLabel(label);
mRegistrationBasicInformationItemForFirstName.SetValue(value);
mRegistrationBasicInformationItemForFirstName.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForFirstName;
}
#Override
public IRegistrationItemView CreateLastNameItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForLastName.SetEventListener(this);
mRegistrationBasicInformationItemForLastName.SetLabel(label);
mRegistrationBasicInformationItemForLastName.SetValue(value);
mRegistrationBasicInformationItemForLastName.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForLastName;
}
#Override
public IRegistrationItemView CreateNickNameItemView(String label, int type, String value, int validationId) {
mRegistrationBasicInformationItemForNickName.SetEventListener(this);
mRegistrationBasicInformationItemForNickName.SetLabel(label);
mRegistrationBasicInformationItemForNickName.SetValue(value);
mRegistrationBasicInformationItemForNickName.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForNickName;
}
#Override
public IRegistrationItemView CreatePracticeItemView(String label, int type, IStringList
valuesList, String defaultValue, int validationId) {
mRegistrationBasicInformationItemForPractice.SetEventListener(this);
mRegistrationBasicInformationItemForPractice.SetLabel(label);
mRegistrationBasicInformationItemForPractice.SetValueList(type, valuesList);
mRegistrationBasicInformationItemForPractice.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_LIST);
return mRegistrationBasicInformationItemForPractice;
}
#Override
public IRegistrationItemView CreateProviderItemView(String label, int type, IStringList
valuesList, String defaultValue, int validationId) {
mRegistrationBasicInformationItemForProvider.SetEventListener(this);
mRegistrationBasicInformationItemForProvider.SetLabel(label);
mRegistrationBasicInformationItemForProvider.SetValueList(type, valuesList);
mRegistrationBasicInformationItemForProvider.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_LIST);
return mRegistrationBasicInformationItemForProvider;
}
#Override
public void ShowPracticeItemView() {
mRegistrationBasicInformationItemForPractice.setVisibility(View.VISIBLE);
}
#Override
public void ShowProviderItemView() {
mRegistrationBasicInformationItemForProvider.setVisibility(View.VISIBLE);
}
#Override
public void RefreshScreen() {
// NA
}
#Override
public void SetGender(int isMale) {
mRegistrationBasicInformationItemForGender.SetValueForSwitch(isMale);
}
#Override
public IRegistrationItemView CreateDobItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForDob.SetEventListener(this);
mRegistrationBasicInformationItemForDob.SetLabel(label);
mRegistrationBasicInformationItemForDob.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
mRegistrationBasicInformationItemForDob.SetValue(value);
return mRegistrationBasicInformationItemForDob;
}
#Override
public IRegistrationItemView CreatePhoneNumberItemView(String label, int type, String value, int validationId) {
mRegistrationBasicInformationItemForPhoneNumber.SetEventListener(this);
mRegistrationBasicInformationItemForPhoneNumber.SetLabel(label);
mRegistrationBasicInformationItemForPhoneNumber.SetValue(value);
mRegistrationBasicInformationItemForPhoneNumber.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForPhoneNumber;
}
#Override
public IRegistrationItemView CreateEmailItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForEmail.SetEventListener(this);
mRegistrationBasicInformationItemForEmail.SetLabel(label);
mRegistrationBasicInformationItemForEmail.SetValue(value);
mRegistrationBasicInformationItemForEmail.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_TEXTFIELD);
mRegistrationBasicInformationItemForEmail.mRegistrationItemTextTypeEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
return mRegistrationBasicInformationItemForEmail;
}
#Override
public IRegistrationItemView CreateGenderItemView(String label, int type,
IStringList valueList, int validationId, int GenderType) {
mRegistrationBasicInformationItemForGender.SetEventListener(this);
mRegistrationBasicInformationItemForGender.SetLabel(label);
mRegistrationBasicInformationItemForGender.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_RADIO_BUTTON);
mRegistrationBasicInformationItemForGender.SetValueList(type, valueList);
mRegistrationBasicInformationItemForGender.clearRadioButtons();
mRegistrationBasicInformationItemForGender.SetValueForSwitch(GenderType);
return mRegistrationBasicInformationItemForGender;
}
#Override
public void OnErrorIconClick(int validationId) {
//NA
}
#Override
public void OnCalendarIconClick() {
mRegistrationBasicInformationController.OnCalendarDateTimeIconClicked();
}
#Override
public void OnSwitchButtonClick(int validationId, boolean isChecked) {
//NA
}
#Override
public void OnRegistrationItemEditCompleted(String content, int validationId) {
mRegistrationBasicInformationController.OnRegistrationItemEditCompleted(validationId, content);
}
#Override
public void OnSpinnerItemSelected(int validationId, int position) {
switch (validationId) {
case RegistrationValidator.VALIDATE_PRACTICE:
mRegistrationBasicInformationController.OnPracticeItemSelected(position);
break;
case RegistrationValidator.VALIDATE_PROVIDER:
mRegistrationBasicInformationController.OnProviderItemSelected(position);
break;
}
}
#Override
public Presenter GetPresenter() {
return mRegistrationBasicInformationController;
}
#Override
public String GetClassName() {
return getClass().getSimpleName();
}
#Override
public void onDestroy() {
super.onDestroy();
OnDestroy();
}
#Override
public void OnDestroy() {
mRegistrationEnterYourBasicInformationLabel = null;
if (mRegistrationBasicInformationItemForFirstName != null) {
mRegistrationBasicInformationItemForFirstName.OnDestroy();
mRegistrationBasicInformationItemForFirstName = null;
}
if (mRegistrationBasicInformationItemForLastName != null) {
mRegistrationBasicInformationItemForLastName.OnDestroy();
mRegistrationBasicInformationItemForLastName = null;
}
if (mRegistrationBasicInformationItemForNickName != null) {
mRegistrationBasicInformationItemForNickName.OnDestroy();
mRegistrationBasicInformationItemForNickName = null;
}
if (mRegistrationBasicInformationItemForPhoneNumber != null) {
mRegistrationBasicInformationItemForPhoneNumber.OnDestroy();
mRegistrationBasicInformationItemForPhoneNumber = null;
}
if (mRegistrationBasicInformationItemForDob != null) {
mRegistrationBasicInformationItemForDob.OnDestroy();
mRegistrationBasicInformationItemForDob = null;
}
if (mRegistrationBasicInformationItemForEmail != null) {
mRegistrationBasicInformationItemForEmail.OnDestroy();
mRegistrationBasicInformationItemForEmail = null;
}
if (mRegistrationBasicInformationItemForGender != null) {
mRegistrationBasicInformationItemForGender.OnDestroy();
mRegistrationBasicInformationItemForGender = null;
}
if (mRegistrationBasicInformationItemForPractice != null) {
mRegistrationBasicInformationItemForPractice.OnDestroy();
mRegistrationBasicInformationItemForPractice = null;
}
if (mRegistrationBasicInformationItemForProvider != null) {
mRegistrationBasicInformationItemForProvider.OnDestroy();
mRegistrationBasicInformationItemForProvider = null;
}
ViewUtils.UnbindReferences(mRegistrationBasicInformationMainLayout);
ViewUtils.UnbindReferences(getView());
}
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
CustomTextInputEditText editText = (CustomTextInputEditText) view;
mRegistrationBasicInformationController.OnRegistrationItemEditCompleted((int) view.getTag()
, editText.getText().toString());
}
}
}

Add numbers from EditTexts

I've created an Activity where I've got an "Add subject" button. When I press it, it creates an item in a ListView, which is formed by an EditText where the user enters a number.
What I want to do is to add the numbers inside the EditTexts of each item created, depending if the user has created 3, 4, 5, etc. items in the ListView, via button.
Here is the code of the Activity:
public class PersActivity extends Activity {
Button start, calcaverage1;
private SubjectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
ListView atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
}
Here is the code of the adapter:
public class SubjectAdapter extends ArrayAdapter<Mark> {
protected static final String LOG_TAG = SubjectAdapter.class.getSimpleName();
private List<Mark> items;
private int layoutResourceId;
private Context context;
public SubjectAdapter(Context context, int layoutResourceId, List<Mark> items) {
super(context, layoutResourceId, items);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MarkHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MarkHolder();
holder.Mark = items.get(position);
holder.removePaymentButton = (ImageButton)row.findViewById(R.id.remove);
holder.removePaymentButton.setTag(holder.Mark);
holder.name = (TextView)row.findViewById(R.id.subjectname);
setNameTextChangeListener(holder);
holder.value = (TextView)row.findViewById(R.id.subjectmark);
setValueTextListeners(holder);
row.setTag(holder);
setupItem(holder);
return row;
}
private void setupItem(MarkHolder holder) {
holder.name.setText(holder.Mark.getName());
holder.value.setText(String.valueOf(holder.Mark.getValue()));
}
public static class MarkHolder {
Mark Mark;
TextView name;
TextView value;
ImageButton removePaymentButton;
}
private void setNameTextChangeListener(final MarkHolder holder) {
holder.name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
holder.Mark.setName(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
private void setValueTextListeners(final MarkHolder holder) {
holder.value.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.Mark.setValue(Double.parseDouble(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading double value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
I've implemented serializable to pass data through the adapter:
public class Mark implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private String name = "";
private double value = 0;
public Mark(String name, double value) {
this.setName(name);
this.setValue(value);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
Hope there's a solution. Thanks!
Here is how you would do it
addNumberFromText()
{
int total=0;
for(int i=0;i<listView.getChildCount();i++)
{
View wantedView = listView.getChildAt(i);
EditText edtText=view.findViewById(R.id.specificEditTextId);
//not checking wheter integer valid or not, Please do so
int value=Integer.parseInt(edtText.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
update your activity from following code
public class PersActivity extends Activity
{
Button start, calcaverage1;
private SubjectAdapter adapter;
ListView atomPaysListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
addNumberFromText()
{
double total=0;
for(int i=0;i<atomPaysListView.getChildCount();i++)
{
View wantedView = atomPaysListView.getChildAt(i);
/*
// if edit text
EditText edt=(EditText)view.findViewById(R.id.editText);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(edt.toString());
*/
//you say edittext, but its a textview or so it seems
TextView txv=(TextView)view.findViewById(R.id.subjectmark);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(txv.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
}

Setting text to a custom dialog class

I am setting text to a custom dialog box. I am getting a NullPointerException. The dialog is called when a listItem is clicked. EDIT, Scroll to the bottom to see updated code. Or See here:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
DialogClass dialogClass = new DialogClass(databaseFightCard.this);
dialogClass.setDialog(homeItem.getHomeItemRedName(), homeItem.getHomeItemRedAge(), homeItem.getHomeItemRedRecord(),
homeItem.getHomeItemRedHeight(), homeItem.getHomeItemRedWeight(), homeItem.getHomeItemRedCity(), homeItem.getHomeItemRedExp(),
homeItem.getHomeItemBlueName(), homeItem.getHomeItemBlueAge(), homeItem.getHomeItemBlueRecord(), homeItem.getHomeItemBlueHeight(),
homeItem.getHomeItemBlueWeight(), homeItem.getHomeItemBlueCity(), homeItem.getHomeItemBlueExp());
dialogClass.show();
}
});
DialogClass
public class DialogClass extends Dialog implements View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public TextView rn, ra, rr, rh, rw, rc, re, bn, ba, br, bh, bw, bc, be;
public void setDialog(String redName, String redAge, String redRecord, String redHeight,
String redWeight, String redCity, String redExp,String blueName, String blueAge,
String blueRecord, String blueHeight,
String blueWeight, String blueCity, String blueExp){
rn = (TextView) findViewById(R.id.tvRName);
ra = (TextView) findViewById(R.id.tvRAge);
rr = (TextView) findViewById(R.id.tvRRecord);
rh = (TextView) findViewById(R.id.tvRHeight);
rw = (TextView) findViewById(R.id.tvRWeight);
rc = (TextView) findViewById(R.id.tvRCity);
re = (TextView) findViewById(R.id.tvRExp);
bn = (TextView) findViewById(R.id.tvBName);
ba = (TextView) findViewById(R.id.tvBAge);
br = (TextView) findViewById(R.id.tvBRecord);
bh = (TextView) findViewById(R.id.tvBHeight);
bw = (TextView) findViewById(R.id.tvBWeight);
bc = (TextView) findViewById(R.id.tvBCity);
be = (TextView) findViewById(R.id.tvBExp);
<----------Where the NullPointer is being thrown----------->
rn.setText(redName);
ra.setText(redAge);
rr.setText(redRecord);
rh.setText(redHeight);
rw.setText(redWeight);
rc.setText(redCity);
re.setText(redExp);
bn.setText(blueName);
ba.setText(blueAge);
br.setText(blueRecord);
bh.setText(blueHeight);
bw.setText(blueWeight);
bc.setText(blueCity);
be.setText(blueExp);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.bPlay);
no = (Button) findViewById(R.id.bDone);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
public DialogClass(Activity a) {
super(a);
this.c = a;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bPlay:
dismiss();
break;
case R.id.bDone:
dismiss();
break;
default:
break;
}
dismiss();
}
}
LogCat
10-05 18:48:01.843 994-994/com.codealchemist.clashmma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.codealchemist.clashmma.DialogClass.setDialog(DialogClass.java:43)
at com.codealchemist.clashmma.databaseFightCard$1.onItemClick(databaseFightCard.java:71)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
at android.widget.AbsListView$1.run(AbsListView.java:3423)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
The LogCat is point to my DialogClass on the line
rn.setText(redName);
I have never set the text to a custom built dialog, so please explain what I am doing wrong.
EDIT DUE TO blackbelt This is how I tried to do a class member. If it is not obvious by my reputation, I am a beginner so please explain a better way to do this:
Changed this in my activity that calls for the dialog
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
DialogClass dialogClass = new DialogClass(homeItem);
dialogClass.show();
}
});
Changed this in my DialogClass
public DialogClass(HomeItem context) {
super(context);
this.hi = context;
}
Then in my onCreate of my DialogClass:
rn.setText(hi.getHomeItemRedName());
bn.setText(hi.getHomeItemBlueName());
Because I had to use Context of HomeItem, or whatever I did I have to make my HomeItem class extend Context. I had to #Override about 80 methods:
public class HomeItem extends Context {
private int HomeItemID;
private String HomeItemRedName, HomeItemRedAge, HomeItemRedRecord, HomeItemRedHeight, HomeItemRedWeight,
HomeItemRedCity, HomeItemRedExp;
private String HomeItemBlueName, HomeItemBlueAge, HomeItemBlueRecord, HomeItemBlueHeight, HomeItemBlueWeight,
HomeItemBlueCity, HomeItemBlueExp;
public int getHomeItemID() {
return HomeItemID;
}
public void setHomeItemID(int ID) {
this.HomeItemID = ID;
}
public String getHomeItemRedName() {
return HomeItemRedName;
}
public void setHomeItemRedName(String Name) {
this.HomeItemRedName = Name;
}
public String getHomeItemRedAge(){
return HomeItemRedAge;
}
public void setHomeItemRedAge(String Age){
if (Age == null)
this.HomeItemRedAge = "Unknown";
this.HomeItemRedAge = Age;
}
public String getHomeItemRedRecord(){
return HomeItemRedRecord;
}
public void setHomeItemRedRecord(String Record){
if (Record == null)
this.HomeItemRedRecord = "Unknown";
this.HomeItemRedRecord = Record;
}
public String getHomeItemRedHeight(){
return HomeItemRedHeight;
}
public void setHomeItemRedHeight(String Height){
if (Height == null)
this.HomeItemRedHeight = "Unknown";
this.HomeItemRedHeight = Height;
}
public String getHomeItemRedWeight(){
return HomeItemRedWeight;
}
public void setHomeItemRedWeight(String Weight){
if (Weight == null)
this.HomeItemRedWeight = "Unknown";
this.HomeItemRedWeight = Weight;
}
public String getHomeItemRedCity(){
return HomeItemRedCity;
}
public void setHomeItemRedCity(String City){
if (City == null)
this.HomeItemRedCity = "Unknown";
this.HomeItemRedCity = City;
}
public String getHomeItemRedExp(){
return HomeItemRedExp;
}
public void setHomeItemRedExp(String Exp){
if (Exp == null)
this.HomeItemRedExp = "Unknown";
this.HomeItemRedExp = Exp;
}
//Blue side
public String getHomeItemBlueName(){
return HomeItemBlueName;
}
public void setHomeItemBlueName(String Name){
this.HomeItemBlueName = Name;
}
public String getHomeItemBlueAge(){
return HomeItemBlueAge;
}
public void setHomeItemBlueAge(String Age){
if (Age == null)
this.HomeItemBlueAge = "Unknown";
this.HomeItemBlueAge = Age;
}
public String getHomeItemBlueRecord(){
return HomeItemBlueRecord;
}
public void setHomeItemBlueRecord(String Record){
if (Record == null)
this.HomeItemBlueRecord = "Unknown";
this.HomeItemBlueRecord = Record;
}
public String getHomeItemBlueHeight(){
return HomeItemBlueHeight;
}
public void setHomeItemBlueHeight(String Height){
if (Height == null)
this.HomeItemBlueHeight = "Unknown";
this.HomeItemBlueHeight = Height;
}
public String getHomeItemBlueWeight(){
return HomeItemBlueWeight;
}
public void setHomeItemBlueWeight(String Weight){
if (Weight == null)
this.HomeItemBlueWeight = "Unknown";
this.HomeItemBlueWeight = Weight;
}
public String getHomeItemBlueCity(){
return HomeItemBlueCity;
}
public void setHomeItemBlueCity(String City){
if (City == null)
this.HomeItemBlueCity = "Unknown";
this.HomeItemBlueCity= City;
}
public String getHomeItemBlueExp(){
return HomeItemBlueExp;
}
public void setHomeItemBlueExp(String Exp){
if (Exp == null)
this.HomeItemBlueExp = "Unknown";
this.HomeItemBlueExp = Exp;
}
#Override
public AssetManager getAssets() {
return null;
}
#Override
public Resources getResources() {
return null;
}
#Override
public PackageManager getPackageManager() {
return null;
}
#Override
public ContentResolver getContentResolver() {
return null;
}
#Override
public Looper getMainLooper() {
return null;
}
#Override
public Context getApplicationContext() {
return null;
}
#Override
public void setTheme(int i) {
}
#Override
public Resources.Theme getTheme() {
return null;
}
#Override
public ClassLoader getClassLoader() {
return null;
}
#Override
public String getPackageName() {
return null;
}
#Override
public ApplicationInfo getApplicationInfo() {
return null;
}
#Override
public String getPackageResourcePath() {
return null;
}
#Override
public String getPackageCodePath() {
return null;
}
#Override
public SharedPreferences getSharedPreferences(String s, int i) {
return null;
}
#Override
public FileInputStream openFileInput(String s) throws FileNotFoundException {
return null;
}
#Override
public FileOutputStream openFileOutput(String s, int i) throws FileNotFoundException {
return null;
}
#Override
public boolean deleteFile(String s) {
return false;
}
#Override
public File getFileStreamPath(String s) {
return null;
}
#Override
public File getFilesDir() {
return null;
}
#Override
public File getExternalFilesDir(String s) {
return null;
}
#Override
public File getObbDir() {
return null;
}
#Override
public File getCacheDir() {
return null;
}
#Override
public File getExternalCacheDir() {
return null;
}
#Override
public String[] fileList() {
return new String[0];
}
#Override
public File getDir(String s, int i) {
return null;
}
#Override
public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory) {
return null;
}
#Override
public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory, DatabaseErrorHandler databaseErrorHandler) {
return null;
}
#Override
public boolean deleteDatabase(String s) {
return false;
}
#Override
public File getDatabasePath(String s) {
return null;
}
#Override
public String[] databaseList() {
return new String[0];
}
#Override
public Drawable getWallpaper() {
return null;
}
#Override
public Drawable peekWallpaper() {
return null;
}
#Override
public int getWallpaperDesiredMinimumWidth() {
return 0;
}
#Override
public int getWallpaperDesiredMinimumHeight() {
return 0;
}
#Override
public void setWallpaper(Bitmap bitmap) throws IOException {
}
#Override
public void setWallpaper(InputStream inputStream) throws IOException {
}
#Override
public void clearWallpaper() throws IOException {
}
#Override
public void startActivity(Intent intent) {
}
#Override
public void startActivity(Intent intent, Bundle bundle) {
}
#Override
public void startActivities(Intent[] intents) {
}
#Override
public void startActivities(Intent[] intents, Bundle bundle) {
}
#Override
public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3) throws IntentSender.SendIntentException {
}
#Override
public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3, Bundle bundle) throws IntentSender.SendIntentException {
}
#Override
public void sendBroadcast(Intent intent) {
}
#Override
public void sendBroadcast(Intent intent, String s) {
}
#Override
public void sendOrderedBroadcast(Intent intent, String s) {
}
#Override
public void sendOrderedBroadcast(Intent intent, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {
}
#Override
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle, String s) {
}
#Override
public void sendOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {
}
#Override
public void sendStickyBroadcast(Intent intent) {
}
#Override
public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {
}
#Override
public void removeStickyBroadcast(Intent intent) {
}
#Override
public void sendStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {
}
#Override
public void removeStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) {
return null;
}
#Override
public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, String s, Handler handler) {
return null;
}
#Override
public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {
}
#Override
public ComponentName startService(Intent intent) {
return null;
}
#Override
public boolean stopService(Intent intent) {
return false;
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return false;
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
}
#Override
public boolean startInstrumentation(ComponentName componentName, String s, Bundle bundle) {
return false;
}
#Override
public Object getSystemService(String s) {
return null;
}
#Override
public int checkPermission(String s, int i, int i2) {
return 0;
}
#Override
public int checkCallingPermission(String s) {
return 0;
}
#Override
public int checkCallingOrSelfPermission(String s) {
return 0;
}
#Override
public void enforcePermission(String s, int i, int i2, String s2) {
}
#Override
public void enforceCallingPermission(String s, String s2) {
}
#Override
public void enforceCallingOrSelfPermission(String s, String s2) {
}
#Override
public void grantUriPermission(String s, Uri uri, int i) {
}
#Override
public void revokeUriPermission(Uri uri, int i) {
}
#Override
public int checkUriPermission(Uri uri, int i, int i2, int i3) {
return 0;
}
#Override
public int checkCallingUriPermission(Uri uri, int i) {
return 0;
}
#Override
public int checkCallingOrSelfUriPermission(Uri uri, int i) {
return 0;
}
#Override
public int checkUriPermission(Uri uri, String s, String s2, int i, int i2, int i3) {
return 0;
}
#Override
public void enforceUriPermission(Uri uri, int i, int i2, int i3, String s) {
}
#Override
public void enforceCallingUriPermission(Uri uri, int i, String s) {
}
#Override
public void enforceCallingOrSelfUriPermission(Uri uri, int i, String s) {
}
#Override
public void enforceUriPermission(Uri uri, String s, String s2, int i, int i2, int i3, String s3) {
}
#Override
public Context createPackageContext(String s, int i) throws PackageManager.NameNotFoundException {
return null;
}
#Override
public Context createConfigurationContext(Configuration configuration) {
return null;
}
#Override
public Context createDisplayContext(Display display) {
return null;
}
Compiling this, in my LogCat, I receive this error:
10-06 18:42:59.465 785-785/com.codealchemist.clashmma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Dialog.<init>(Dialog.java:154)
at android.app.Dialog.<init>(Dialog.java:131)
at com.codealchemist.clashmma.DialogClass.<init>(DialogClass.java:83)
at com.codealchemist.clashmma.databaseFightCard$1.onItemClick(databaseFightCard.java:70)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
at android.widget.AbsListView$1.run(AbsListView.java:3423)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I ALSO TRIED THIS
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
final Dialog dialog = new Dialog(databaseFightCard.this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
WindowManager.LayoutParams lp = (dialog.getWindow().getAttributes());
lp.dimAmount = 0.5f;
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
dialog.setContentView(R.layout.custom_dialog);
Button play = (Button) findViewById(R.id.bPlay);
Button done = (Button) findViewById(R.id.bDone);
TextView rn = (TextView) findViewById(R.id.tvRName);
TextView ra = (TextView) findViewById(R.id.tvRAge);
TextView rr = (TextView) findViewById(R.id.tvRRecord);
TextView rh = (TextView) findViewById(R.id.tvRHeight);
TextView rw = (TextView) findViewById(R.id.tvRWeight);
TextView rc = (TextView) findViewById(R.id.tvRCity);
TextView re = (TextView) findViewById(R.id.tvRExp);
TextView bn = (TextView) findViewById(R.id.tvBName);
TextView ba = (TextView) findViewById(R.id.tvBAge);
TextView br = (TextView) findViewById(R.id.tvBRecord);
TextView bh = (TextView) findViewById(R.id.tvBHeight);
TextView bw = (TextView) findViewById(R.id.tvBWeight);
TextView bc = (TextView) findViewById(R.id.tvBCity);
TextView be = (TextView) findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName()+"");
ra.setText(homeItem.getHomeItemRedAge()+"");
rr.setText(homeItem.getHomeItemRedRecord()+"");
rh.setText(homeItem.getHomeItemRedHeight()+"");
rw.setText(homeItem.getHomeItemRedWeight()+"");
rc.setText(homeItem.getHomeItemRedCity()+"");
re.setText(homeItem.getHomeItemRedExp()+"");
bn.setText(homeItem.getHomeItemBlueName()+"");
ba.setText(homeItem.getHomeItemBlueAge()+"");
br.setText(homeItem.getHomeItemBlueRecord()+"");
bh.setText(homeItem.getHomeItemBlueHeight()+"");
bw.setText(homeItem.getHomeItemBlueWeight()+"");
bc.setText(homeItem.getHomeItemBlueCity()+"");
be.setText(homeItem.getHomeItemBlueExp()+"");
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
Still getting NullPointerException on
rn.setText(homeItem.getHomeItemRedName()+"");
setDialog is called before the Dialog's onCreate . Instead of passing all the Strings to setDialog you can pass a HomeItem reference and you can keep it as class member. Inside the onCreate, after setContentView you can perform all the findViewById and set the text accordingly
Edit
public class DialogClass extends Dialog implements View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public TextView rn, ra, rr, rh, rw, rc, re, bn, ba, br, bh, bw, bc, be;
private HomeItem homeItem;
public void setDialog(HomeItem homeItem){
this.homeItem = homeItem;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.bPlay);
no = (Button) findViewById(R.id.bDone);
yes.setOnClickListener(this);
no.setOnClickListener(this);
rn = (TextView) findViewById(R.id.tvRName);
ra = (TextView) findViewById(R.id.tvRAge);
rr = (TextView) findViewById(R.id.tvRRecord);
rh = (TextView) findViewById(R.id.tvRHeight);
rw = (TextView) findViewById(R.id.tvRWeight);
rc = (TextView) findViewById(R.id.tvRCity);
re = (TextView) findViewById(R.id.tvRExp);
bn = (TextView) findViewById(R.id.tvBName);
ba = (TextView) findViewById(R.id.tvBAge);
br = (TextView) findViewById(R.id.tvBRecord);
bh = (TextView) findViewById(R.id.tvBHeight);
bw = (TextView) findViewById(R.id.tvBWeight);
bc = (TextView) findViewById(R.id.tvBCity);
be = (TextView) findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName());
// the rest of your code
}
// other code
}
This was actually really simple. I just ditched the Dialog class, and did it all here in my onClick.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
final Dialog dialog = new Dialog(databaseFightCard.this);
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.requestFeature(window.FEATURE_NO_TITLE);
LayoutInflater inflater = (LayoutInflater) databaseFightCard.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout relative = (RelativeLayout) inflater.inflate(R.layout.custom_dialog, null, false);
dialog.setContentView(relative);
Button play = (Button) relative.findViewById(R.id.bPlay);
Button done = (Button) relative.findViewById(R.id.bDone);
TextView rn = (TextView) relative.findViewById(R.id.tvRName);
TextView ra = (TextView) relative.findViewById(R.id.tvRAge);
TextView rr = (TextView) relative.findViewById(R.id.tvRRecord);
TextView rh = (TextView) relative.findViewById(R.id.tvRHeight);
TextView rw = (TextView) relative.findViewById(R.id.tvRWeight);
TextView rc = (TextView) relative.findViewById(R.id.tvRCity);
TextView re = (TextView) relative.findViewById(R.id.tvRExp);
TextView bn = (TextView) relative.findViewById(R.id.tvBName);
TextView ba = (TextView) relative.findViewById(R.id.tvBAge);
TextView br = (TextView) relative.findViewById(R.id.tvBRecord);
TextView bh = (TextView) relative.findViewById(R.id.tvBHeight);
TextView bw = (TextView) relative.findViewById(R.id.tvBWeight);
TextView bc = (TextView) relative.findViewById(R.id.tvBCity);
TextView be = (TextView) relative.findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName()+"");
ra.setText(homeItem.getHomeItemRedAge()+"");
rr.setText(homeItem.getHomeItemRedRecord()+"");
rh.setText(homeItem.getHomeItemRedHeight()+"");
rw.setText(homeItem.getHomeItemRedWeight()+"");
rc.setText(homeItem.getHomeItemRedCity()+"");
re.setText(homeItem.getHomeItemRedExp()+"");
bn.setText(homeItem.getHomeItemBlueName()+"");
ba.setText(homeItem.getHomeItemBlueAge()+"");
br.setText(homeItem.getHomeItemBlueRecord()+"");
bh.setText(homeItem.getHomeItemBlueHeight()+"");
bw.setText(homeItem.getHomeItemBlueWeight()+"");
bc.setText(homeItem.getHomeItemBlueCity()+"");
be.setText(homeItem.getHomeItemBlueExp()+"");
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});

Categories

Resources