I am creating an app in android studios that requires the user to select a child item from an expandable listview on one activity and for it to be displayed on another activity. I'm new to java and android studios and still dont understand how to do this really. If anyone has any sample code or can help that would be great, thanks!
You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView.
Here there's a tutorial for using a ExpandableListView and it shows how to set a ClickListener for the elements.
And here there's the Android developer's documentation which shows how to create and open a new Activity from a button's click.
**You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView and create the xml file for child and parent.child will be Expandable TextView **
**layout 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:id="#+id/activity_main"
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.elite_android.explistview1.MainActivity">
<RelativeLayout
android:id="#+id/main_number_picker_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp">
<NumberPicker
android:id="#+id/main_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Next" />
<TextView
android:id="#+id/main_txt_patient_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/main_number_picker"
android:text="Select number of patient"
android:textColor="#color/colorAccent"
android:layout_marginLeft="80dp"/>
</RelativeLayout>
<ExpandableListView
android:id="#+id/exp_Listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/main_number_picker_layout">
</ExpandableListView>
</RelativeLayout>
**Main Activity.java file**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.view.View.OnFocusChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
private MyAdapter mAdapter;
ExpandableListView expand;
NumberPicker numberPicker;
private List<String> headerItems;
private ArrayList childDetails;
private HashMap<String, List<String>> childList;
private Context ctx;
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the EditText
editText1 = (EditText) findViewById(R.id.child_item);
// //set the onFocusChange listener
// // editText1.setOnFocusChangeListener(editText1.getOnFocusChangeListener());
//
//// //get reference to EditText
//// editText2 = (EditText) findViewById(R.id.sequence);
//// // set the on focusChange listner
//// editText2.setOnFocusChangeListener(editText2.getOnFocusChangeListener());
//
// //Generate list View from ArrayList;
//
//
// EditText editText = (EditText) findViewById(R.id.child_item);
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
//
//
//// editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// // #Override
// // public void onFocusChange(View v, boolean hasFocus) {
// // //editText.setOnFocusChangeListener();
// // return;
// // }
// //});
//
String[] numbers = new String[10];
for (int count = 0; count < 10; count++)
numbers[count] = String.valueOf(count);
numberPicker = (NumberPicker) findViewById(R.id.main_number_picker);
numberPicker.setMaxValue(numbers.length);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
generateListItems(newVal);
loadRecycleView();
}
});
}
private void generateListItems(int childCount) {
if (headerItems != null)
headerItems.clear();
else
headerItems = new ArrayList<>();
if (childList != null)
childList.clear();
else
childList = new HashMap();
if (childDetails == null) {
childDetails = new ArrayList();
childDetails.add("Name");
childDetails.add("Age");
childDetails.add("Gender");
}
// Put header items
for (int count = 0; count < childCount; count++) {
headerItems.add(" Parent " + count);
childList.put(headerItems.get(count), childDetails);
}
}
private void loadRecycleView() {
if (expandableListView == null) {
expandableListView = (ExpandableListView) findViewById(R.id.exp_Listview);
mAdapter = new MyAdapter(this, headerItems, childList);
expandableListView.setAdapter(mAdapter);
} else {
expandableListView.invalidate();
mAdapter.setHeaderData(headerItems);
mAdapter.setListData(childList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
**Adapter class.java**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnFocusChangeListener;
/**
* Created by ELITE-ANDROID on 28-02-2017.
*/
// this is provides all needs methods implementing an Expandable List VIew
public class MyAdapter extends BaseExpandableListAdapter {
// We need some Variables here so therer are some Variables here
private List<String> header_titles; // This is for Representing the HeadLine(Array list)
private HashMap<String, List<String>> child_titles; // defin the HashMap for the child item how to Represent the Parent Handing so Hash Map, need some Variables
private Context ctx;
private NumberPicker numberPicker;
EditText editText;
View view;
private static LayoutInflater inflater = null;
//for initalized for all Variables we need some Constructor
public MyAdapter(Context context, List<String> header_titles, HashMap<String, List<String>> child_titles) {
super();
this.ctx = context;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
public void refreshHeader_titles(List<String> events) {
this.header_titles.clear();
this.header_titles.addAll(header_titles);
notifyDataSetChanged();
}
;
#Override
// From this Override method How to Return how many elements are the Group count like parent
public int getGroupCount() {
return header_titles.size();
}
#Override
//here the number of child items are in each heading. There are three Heading - PAtien Name ,Age, Gender
public int getChildrenCount(int groupPosition) {
// Log.d("xxx", )
return child_titles.get(header_titles.get(groupPosition)).size(); //how to Return the size of HashMap
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
// here how to retuen child items on the particular headings and Positions.
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
//return the groupo position
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
// Here return the Group View
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// ListViewHolder viewHolder;
// if (view == null) {
// viewHolder = new ListViewHolder();
// LayoutInflater inflater = context.getLayoutInflater();
// view = inflater.inflate(R.layout.listitems, null, true);
// viewHolder.itmName = (TextView) view.findViewById(R.id.Item_name);
// viewHolder.itmPrice = (EditText) view.findViewById(R.id.Item_price);
// view.setTag(viewHolder);
// } else {
// viewHolder = (ListViewHolder) view.getTag();
//// loadSavedValues();
// }
// Here how to get the Heading Title here Decalered String Variables, now how to get title of heading from getGroup methods so simple call Backed Methods.
String title = (String) this.getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.prent, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setText(title); // for Heading bold style ,title
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String) this.getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child, null);
}
String cellData = child_titles.get(header_titles.get(groupPosition)).get(childPosition);
EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.d("xxxx", "Has focus " + hasFocus);
if (!hasFocus) {
// int itemIndex = View.getId();
// String enteredName = ((EditText)v).getText().toString();
// selttems.put(itemIndex, enteredName);
} else {
}
return;
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setListData(HashMap<String, List<String>> lData) {
child_titles = lData;
}
public void setHeaderData(List<String> hData) {
header_titles = hData;
}
}
**child.Xml file**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffff">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/child_item"
android:textSize="25dp"
android:textStyle="bold"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<!--<EditText-->
<!--android:id="#+id/sequence"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentLeft="true"-->
<!--android:layout_alignParentTop="true"-->
<!--android:paddingLeft="35sp"-->
<!--android:layout_marginRight="10dp"-->
<!--android:textAppearance="?android:attr/textAppearanceMedium" />-->
</LinearLayout>
<!--This Layout File Represent the Child Items.
This Field Represent the Child Item IN the List VIew -->
**parent.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="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textColor="#color/colorAccent"
android:textSize="25dp" />
</LinearLayout>
<!--This Layout file for Heading -Lines.-->
Related
I have an Expandable ListView(EXLV) whose every Child Item has an EditText, And There is a Button outside the EXLV. It's been a week I'm messing with it.
I want to get values/Data entered in EditTexts on button Click. Because the values I enter are regenerated (I Don't know why).
Any Help would be very Appreciated.
Here is a Link to whole Project in case: https://drive.google.com/file/d/1YsCb23-wL_KBgj2braqT59mPezRhSS28/view?usp=sharing
MainActiviy.java:
package com.lvexpandable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Handler;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
final int snnn=1857;
Button btn;
EditText edt;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] mStrings = new String[20];
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
public void btnClick(View v){
//I want to get values entered in EditTexts here. Maybe using SharedPref, in a List<> or whatever.
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
// Adding child data
listDataHeader.add("PG");
listDataHeader.add("Nursery");
// Adding child data
List<String> pg = new ArrayList<String>();
pg.add("PG1: ");
pg.add("PG2: ");
pg.add("PG3: ");
pg.add("PG4: ");
pg.add("PG5: ");
pg.add("PG6: ");
pg.add("PG7: ");
pg.add("PG8: ");
pg.add("PG9: ");
pg.add("PG10: ");
pg.add("PG11: ");
pg.add("PG12: ");
pg.add("PG13: ");
pg.add("PG14: ");
pg.add("PG15: ");
List<String> nur = new ArrayList<String>();
nur.add("Object A ");
nur.add("Obj B: ");
nur.add("Obj C:");
listDataChild.put(listDataHeader.get(0), pg); // Header, Child data
listDataChild.put(listDataHeader.get(1), nur);
}
}
ExpandableListAdapter.java:
package com.lvexpandable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lvexpandable.MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="50dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ExpandableListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="400dp" />
<Button
android:onClick="btnClick"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="230dp"
android:text="Button"
tools:layout_editor_absoluteX="257dp"
tools:layout_editor_absoluteY="360dp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
If anyone has a Confusion, Feel free to Ask :)
The Thing you are Trying to do is Certainly Possible, But Complex:
Add A Button in Every Child Item
When User types in Child 0, He Must Press that Child's Button (on Button Click, Save the value in array on index[childPosition]). In
this Way, Array[0] will have text of Child 1, Similar for Next
Children.
(Step 3 and Further are Optional)
If You Don't like this Design (as User needs to press button every time he enters a value, Refer to Step 4)
Set the Visibility of the Button(which was added in Step 1) to INVISIBLE
Add a TextWatcher (TextChangedListener) for EditText in ChildItem (It will getText entered > Save it in Array[] > Click the Button itself as Soon as User leaves the Current EditText). As:
edt.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) {
if(edt.getText().toString()==""&&edt.getText().toString().equals(null)){
}
else {
edt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)//Perform Click when edt loses Focus {
btn.callOnClick();
}
}
});
}
}});
Now the Button Click will be like:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edt.getText().toString().equals("")){
}
else {
Toast.makeText(view.getContext(),"Entered: "+edt.getText().toString(),Toast.LENGTH_SHORT).show();
myStringArray[childPosition]=edt.getText().toString();
edt.setText("");
}
}
});
this is a small application which asks some questions and then it will show answers. When we finish answering all the questions, new activity appears and shows us the all the answers except the last one. I searched this problem and saw answers but none of them is working in my case. Thanks for any kind of help.
This is my code:
XML code for the main layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.itrio.iqtest.Result_QA"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Answers"
android:textSize="22sp"
android:textStyle="bold"
android:layout_margin="20dp"/>
<ListView
android:id="#+id/result_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Another XML custom view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:padding="10dp">
<TextView
android:id="#+id/question_result"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:textSize="18sp"
android:textStyle="bold">
</TextView>
<View
android:layout_width="match_parent"
android:layout_height="10dp"/>
<TextView
android:textStyle="italic"
android:id="#+id/answer_result"
android:layout_width="fill_parent"
android:textSize="18sp"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
Here's the code for questions:
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
public class Genius extends AppCompatActivity {
private TextView question_view;
private Button mNext;
int currentQ = 0;
RadioGroup genius_rg;
RadioButton op1, op2, op3, op4,checked;
private int score;
int turns=0;
boolean check= false, shuffle = true;
String[] questions = new String[8];
String[] answers = new String[8];
//Keys
private static final String Question_Index_key = "Index value of Questions";
private static final String Checked_Radio = "Selected radio Button";
private static final String Is_Radio_Checked = "ISC";
private static final String Do_Not_Shuffle_Again = "Dont' shuffle";
public static final String Result_Questions = "questions to display at result activity";
public static final String Result_Answers = "answers to display at result activity";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(Question_Index_key,currentQ);
outState.putInt(Checked_Radio,genius_rg.getCheckedRadioButtonId());
outState.putBoolean(Is_Radio_Checked,check);
outState.putBoolean(Do_Not_Shuffle_Again, shuffle);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Dialog alert_exit = new QuizExitAlert(Genius.this);
alert_exit.show();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Changes 'back' button action
if (keyCode == KeyEvent.KEYCODE_BACK) {
Dialog alert_exit = new QuizExitAlert(Genius.this);
alert_exit.show();
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_genius);
if (savedInstanceState != null) {
currentQ = savedInstanceState.getInt(Question_Index_key);
if (savedInstanceState.getBoolean(Is_Radio_Checked)) {
checked = (RadioButton) findViewById(savedInstanceState.getInt(Checked_Radio));
checked.setChecked(true);
}
shuffle = savedInstanceState.getBoolean(Do_Not_Shuffle_Again);
}
question_view = (TextView) findViewById(R.id.question_genius);
genius_rg = (RadioGroup) findViewById(R.id.radio_genius);
op1 = (RadioButton) findViewById(R.id.g_op1);
op2 = (RadioButton) findViewById(R.id.g_op2);
op3 = (RadioButton) findViewById(R.id.g_op3);
op4 = (RadioButton) findViewById(R.id.g_op4);
Collections.shuffle(bank);
question_view.setText(bank.get(currentQ).getQ());
op1.setText(bank.get(currentQ).getOp1());
op2.setText(bank.get(currentQ).getOp2());
op3.setText(bank.get(currentQ).getOp3());
op4.setText(bank.get(currentQ).getOp4());
mNext = (Button) findViewById(R.id.next_genius);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turns++;
if (turns >= 8) {
new AlertDialog.Builder(Genius.this)
.setTitle("Done!!!")
.setMessage("You have answered all the questions.")
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent result = new Intent(Genius.this,Result_QA.class);
result.putExtra(Result_Questions, questions);
result.putExtra(Result_Answers, answers);
startActivity(result);
}
}).show();
}else {
if (op1.isChecked() || op2.isChecked() || op3.isChecked() || op4.isChecked()) {
checked = (RadioButton) findViewById(genius_rg.getCheckedRadioButtonId());
if (bank.get(currentQ).getAns() == checked.getText()) {
score += 10;
}
questions[currentQ] = bank.get(currentQ).getQ();
answers[currentQ] = bank.get(currentQ).getAns();
genius_rg.clearCheck();
currentQ++;
question_view.setText(bank.get(currentQ).getQ());
op1.setText(bank.get(currentQ).getOp1());
op2.setText(bank.get(currentQ).getOp2());
op3.setText(bank.get(currentQ).getOp3());
op4.setText(bank.get(currentQ).getOp4());
} else {
Toast.makeText(Genius.this, "Select an option to proceed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
Here's the code for LisView Activity:
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
public class Result_QA extends Activity {
ListView result;
ReslutListViewAdapter reslutListViewAdapter;
String[] ques, ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result__q);
Bundle b= getIntent().getExtras();
ques = b.getStringArray(new Genius().Result_Questions);
ans = b.getStringArray(new Genius().Result_Answers);
result = (ListView) findViewById(R.id.result_view);
reslutListViewAdapter = new ReslutListViewAdapter(this, ques, ans);
System.out.println("adapter => "+reslutListViewAdapter.getCount());
result.setAdapter(reslutListViewAdapter);
}
}
Code for ListViewAdapter class:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ReslutListViewAdapter extends BaseAdapter {
Activity context;
String[] questions;
String[] answers;
public ReslutListViewAdapter(Activity con, String[] ques, String[] ans){
super();
context = con;
questions = ques;
answers = ans;
}
#Override
public int getCount() {
return questions.length;
}
private class ViewHolder {
TextView mQ;
TextView mA;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.result_listadapter, null);
holder = new ViewHolder();
holder.mQ = (TextView) convertView.findViewById(R.id.question_result);
holder.mA = (TextView) convertView.findViewById(R.id.answer_result);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.mQ.setText(questions[position]);
holder.mA.setText(answers[position]);
return convertView;
}
}
First of all listview is old one Recyclerview had came, which makes our work easier and lot more improvements have been done in RecyclerView to make developer work easier.
Coming to this issue, ListView doesn't support wrap_content. So change the height and width of ListView to match_parent. Then in adapter xml file the parent layout height should be wrap_content, but you have mentioned it as match_parent, so change that also to wrap_content. Hopefully, this should solve your problem. If the above solution didn't work, then try by removing the padding and margin in the adapter XML layout(from the parent layout in result_listadapter.xml file).
FYI fill_parent is deprecated and we are supposed to use match_parent instead of that. So avoid using the fill_parent.
Hope this helps:)
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>
just try
messageAdapter = new ChatAdapter(MessageListActivity .this);
This question already has answers here:
How to extract the text from the selected item on the listView
(14 answers)
Listview with Details
(4 answers)
Closed 7 years ago.
I have a Listview with 3 Textviews, and I want to retrieve the specific data from these textviews on the clicked Item. For now I'm trying to get the data from the first textview. The problem is, it doesn't matter if I click on Item 1, 2, 3 or etc because I'll always get the text from first Item on the listview. I think the problem is because I don't know how to specific which data I want, from which Item. This is my code:
estoque.java:
package com.example.asus.mingausfashionmoda;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class estoque extends ListActivity {
String qntES;
String pcES;
String pvES;
//list
protected List<ParseObject> mObject;
String variable = "camisa";
// declare class variables
private ArrayList<Item> m_parts = new ArrayList<Item>();
private Runnable viewParts;
private ItemAdapter m_adapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.estoque_main);
// instantiate our ItemAdapter class
m_adapter = new ItemAdapter(this, R.layout.list_item, m_parts);
setListAdapter(m_adapter);
// here we are defining our runnable thread.
viewParts = new Runnable(){
public void run(){
handler.sendEmptyMessage(0);
}
};
// here we call the thread we just defined - it is sent to the handler below.
Thread thread = new Thread(null, viewParts, "MagentoBackground");
thread.start();
}
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
// create some objects
// here is where you could also request data from a server
// and then create objects from that data.
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(variable);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> statuslist, ParseException e) {
if(e != null){
//data successfully retrieved
Toast.makeText(estoque.this, "Houve um erro inesperado, tente novamente mais tarde", Toast.LENGTH_LONG).show();
}else{
//something went wrong
mObject = statuslist;
for(int i = 0; i<mObject.size(); i++) {
ParseObject statusObject = mObject.get(i);
String username = statusObject.getString("user");
Number qntE = statusObject.getNumber("qnt");
qntES = String.valueOf(qntE);
Number pcE = statusObject.getNumber("precoC");
pcES = String.valueOf(pcE);
Number pvE = statusObject.getNumber("precoV");
pvES = String.valueOf(pvE);
m_parts.add(new Item(qntES, pvES, pcES));
m_adapter = new ItemAdapter(estoque.this, R.layout.list_item, m_parts);
setListAdapter(m_adapter);
}
}
}
});
final ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
TextView ttd = (TextView)findViewById(R.id.toptextdata);
System.out.println(ttd.getText().toString());
}
});
}
};
}
ItemAdapter.java:
package com.example.asus.mingausfashionmoda;
/**
* Created by ASUS on 21/12/2015.
*/
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ItemAdapter extends ArrayAdapter<Item> {
// declaring our ArrayList of items
private ArrayList<Item> objects;
/* here we must override the constructor for ArrayAdapter
* the only variable we care about now is ArrayList<Item> objects,
* because it is the list of objects we want to display.
*/
public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(int position, View convertView, ViewGroup parent){
// assign the view we are converting to a local variable
View v = convertView;
/** v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CARALHO VC CRICOU" + objects);
}
}); */
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
/*
* Recall that the variable position is sent in as an argument to this method.
* The variable simply refers to the position of the current object in the list. (The ArrayAdapter
* iterates through the list we sent it)
*
* Therefore, i refers to the current Item object.
*/
Item i = objects.get(position);
if (i != null) {
// This is how you obtain a reference to the TextViews.
// These TextViews are created in the XML files we defined.
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
TextView mt = (TextView) v.findViewById(R.id.middletext);
TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView btd = (TextView) v.findViewById(R.id.desctext);
// check to see if each individual textview is null.
// if not, assign some text!
if (tt != null){
tt.setText("Quantidade: ");
}
if (ttd != null){
ttd.setText(i.getName());
}
if (mt != null){
mt.setText("Preco compra: ");
}
if (mtd != null){
mtd.setText("$" + i.getPrice());
}
if (bt != null){
bt.setText("Preco venda: ");
}
if (btd != null){
btd.setText(i.getDetails());
}
}
// the view must be returned to our activity
return v;
}
}
Item.java:
package com.example.asus.mingausfashionmoda;
import android.widget.TextView;
public class Item {
private String details;
private String name;
private String price;
public Item(){
}
public Item(String i, String d, String p){
this.details = d;
this.name = i;
this.price = p;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
estoque_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnSelecionarQuery"
android:text="ROUPA"
/>
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
/>
<TextView
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No items to display."/>
</LinearLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<!-- Item Name -->
<TextView
android:id="#+id/toptext"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:singleLine="true"
android:ellipsize="marquee"
/>
<!-- Actual Item Name Data -->
<TextView
android:id="#+id/toptextdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/toptext"
android:singleLine="true"
android:ellipsize="marquee"
/>
<!-- Price Tag -->
<TextView
android:id="#+id/middletext"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentLeft="true"
android:layout_below="#id/toptext"
android:textStyle="bold"
android:gravity="center_vertical"
/>
<!-- Actual Price Data -->
<TextView
android:id="#+id/middletextdata"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentRight="true"
android:layout_below="#id/toptext"
android:layout_toRightOf="#id/middletext"
android:gravity="center_vertical"
/>
<!-- Description Tag -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/middletext"
android:textStyle="bold"
android:id="#+id/bottomtext"
android:singleLine="false"
/>
<!-- This is the actual description -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_below="#id/bottomtext"
android:id="#+id/desctext"
android:singleLine="false"
/>
</RelativeLayout>
To make it easier for your understanding, this is where I get the clicked item from the listview and try to get it's first textview text(This is on estoque.java):
final ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
TextView ttd = (TextView)findViewById(R.id.toptextdata);
System.out.println(ttd.getText().toString());
}
});
Thanks.
Want to access View from clicked row layout of ListView, use second parameter of onItemClick to call findViewById like:
TextView ttd = (TextView) myView.findViewById(R.id.toptextdata);
Make your textView final and instead of using listItemClickListner use onclickListener on each textview in the getView().
I want to use ExpandableListView inside ScrollView with other views but i faced the problem of self scroller in ExpandableListView l tried to disable it but the problem is with the height of the ExpandableListView and the layout it's inside.
So i want to
Disable ExpandableListView scroll
Resize ExpandableListView & LinearLayout that contains when groupView is clicked
I googled a solution and i found one for that works for ListView only
Listview in ScrollView
I want to make the same workout but with ExpandableListView (with custom Adapter).
Here is My Code:
MainActivity.java
package fablabegypt.android.expandablelistview2;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ActionBarActivity {
mListAdapter listAdapter;
ExpandableListView expListView;
LinearLayout linearLayout;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_holder);
prepareListData();
expListView = (ExpandableListView) findViewById(R.id.expand_list);
//expListView.setScrollContainer(false);
expListView.setHorizontalScrollBarEnabled(false);
expListView.setVerticalScrollBarEnabled(false);
expListView.setFastScrollEnabled(false);
expListView.setSmoothScrollbarEnabled(false);
//expListView.setOverscrollHeader(null);
expListView.setFooterDividersEnabled(false);
//expListView.setOverscrollFooter(null);
//expListView.setVerticalFadingEdgeEnabled(false);
//expListView.setHorizontalFadingEdgeEnabled(false);
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
return true;
}
});
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if (parent.isGroupExpanded(groupPosition)) {
parent.collapseGroup(groupPosition);
} else {
parent.expandGroup(groupPosition);
}
//telling the listView we have handled the group click, and don't want the default actions.
return true;
}
});
expListView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
return false;
}else {
}
return true;
}
});
listAdapter = new mListAdapter(this, listDataHeader,listDataChild);
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");
// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");
List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");
List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");
listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
listDataChild.put(listDataHeader.get(1), nowShowing);
listDataChild.put(listDataHeader.get(2), comingSoon);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
mListAdapter.java
package fablabegypt.android.expandablelistview2;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
/**
* Created by Mouso on 4/27/2015.
*/
public class mListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> header_list;
private HashMap<String, List<String>> children_data_list;
public mListAdapter(Context context,List<String> header_list,HashMap<String,List<String>> children_data_list){
this.context = context;
this.header_list = header_list;
this.children_data_list = children_data_list;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getGroupCount() {
return this.children_data_list.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.children_data_list.get(this.header_list.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.header_list.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.children_data_list.get(this.header_list.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final String headerText = (String) getGroup(groupPosition);
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_group,null);
}
TextView headerTxt = (TextView) convertView.findViewById(R.id.list_group_txt);
headerTxt.setTextSize(20);
headerTxt.setText(headerText);
//Log.d("Mouso",headerText);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition,childPosition);
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item,null);
}
TextView childTxt = (TextView) convertView.findViewById(R.id.list_child_txt);
childTxt.setText(childText);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public boolean isEmpty() {
if (header_list.size() > 0)
return true;
return false;
}
#Override
public void onGroupExpanded(int groupPosition) {
}
#Override
public void onGroupCollapsed(int groupPosition) {
}
#Override
public long getCombinedChildId(long groupId, long childId) {
return (groupId*100)+childId;
}
#Override
public long getCombinedGroupId(long groupId) {
return groupId;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="500px"
android:fillViewport="true">
<LinearLayout
android:id="#+id/linear_holder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="we 7yat 3neak we fadaha 3neya \n\n\n dana ba7ebak ad 3naya"/>
<ExpandableListView
android:id="#+id/expand_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:isScrollContainer="false">
</ExpandableListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/list_group_txt"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/list_child_txt"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
My Try for implmenting the workout
Helper.java
package fablabegypt.android.expandablelistview2;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* Created by Mouso on 4/29/2015.
*/
public class ListViewHelper {
public static void getListViewSize(ExpandableListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int groupSize = 0; groupSize < myListAdapter.getGroupCount(); groupSize++) {
View listItem = myListAdapter.getGroupView(groupSize, false, null, myListView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
for (int size = 0; size < myListAdapter.getChildrenCount(groupSize); size++) {
if (size == myListAdapter.getChildrenCount(groupSize)-1)
listItem = myListAdapter.getChildView(groupSize, size, true, null, myListView);
listItem = myListAdapter.getChildView(groupSize, size, false, null, myListView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getGroupCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
Log.d("mouso", "height of listItem:"+String.valueOf(totalHeight));
}
//Read more: http://www.androidhub4you.com/2012/12/listview-into-scrollview-in-android.html#ixzz3Yh4m4MPG
}
Extend the ExpandableListView class and set expand to false
public class CustomExpandableListView extends ExpandableListView {
boolean expanded = false;
public CustomExpandableListView (Context context) {
super(context);
}
public CustomExpandableListView (Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomExpandableListView (Context context, AttributeSet attrs,int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isExpanded()) {
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
In your activity class
CustomExpandableListView customExpandableListView = (CustomExpandableListView ) findViewById(R.id.expandable_list);
customExpandableListView .setExpanded(true);
Layout file
<com.xxx.xxx.util.ExpandableHeightListView
android:id="#+id/expandable_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Now It will work within a scroll view
I have same problemm
I solve this problem adding header and footer in ExpandableListView
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ExpandableListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ExpandableListView>
</LinearLayout>
</ScrollView>
/// add header
ExpandableListView listview
ViewGroup headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.item_header, listview, false);
listview.addHeaderView(headerView_right);
*/// add footer*
ViewGroup footerview= (ViewGroup) getLayoutInflater().inflate(R.layout.item_footer, listview, false);
listview.addFooterView(headerView_right);
It is ALWAYS a very bad idea to put a view that has it's own scrolling functionality inside another view with scrolling functionality. This can lead to touch actions being intercepted by the wrong view, poor performance, etc. Also, from your main layout, you don't seem to be using the ScrollView for anything other than making the TextView scroll with the list view. Why not add it as a header view? expListView.setHeaderView(View) and inflate the textview into it.
As I can see in your "activity_main.layout" I think you want to put the ExpandableListView to make the textview scroll always with the List, isn't it?
You have two solutions.
-The prettiest and easiest solution is to put the textview as a header of the ExpandableListView using
list.addHeaderView(listHeader,null,false);
important: Using "false" as the third the header can't be clicked as a row.
-The other solution is to call "getListViewSize()" every time you call "parent.collapseGroup(groupPosition)" or "parent.expandGroup(groupPosition);"
I know using a listview inside a scrollview is not recommended but sometimes is useful. Unfortunately this isn't that case, I recommend to use the first solution.
I hope I could help you.