I need AutoCompleteTextView in editable format on clicking image icon - java

Here I have an AutoCompleteTextView and an image view it;s an arrow that is placed just right side of this AutoCompleteTextView. When I click on that image icon I need this AutoCompleteTextView to be in editable form means the same effect when we touch directly in this AutoCompleteTextView
<AutoCompleteTextView
android:background="#android:color/transparent"
android:id="#+id/auto"
android:textStyle="bold"
android:hint="Select Location"
android:textColor="#ffffff"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:dropDownWidth="match_parent"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="dropclick"
android:src="#mipmap/ic_keyboard_arrow_down_black_24dp"/>
</android.support.v7.widget.Toolbar>

Answer by Quessema Aroua is good but here's what you can do without a library.
Implement this code in XML.
<AutoCompleteTextView
android:layout_width="0dp"
android:layout_height="30dp"
android:hint="#string/source"
android:id="#+id/actv5"
app:layout_constraintTop_toBottomOf="#+id/actv4"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="#drawable/side_nav_bar"
android:textAlignment="center"
android:gravity="center"
android:layout_marginTop="50dp"
android:dropDownHeight="155dp"
android:cursorVisible="false"/>
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:id="#+id/imv2"
android:src="#drawable/ic_keyboard_arrow_down_black_24dp"
app:layout_constraintTop_toTopOf="#+id/actv5"
app:layout_constraintBottom_toBottomOf="#+id/actv5"
app:layout_constraintRight_toRightOf="#+id/actv5"
/>
You can choose whatever layout you need but mine is ConstraintLayout.
And this in YourActivity.java
locnames = getResources().getStringArray(R.array.Loc_names);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_dropdown_item,
locnames);
autoText1 =(AutoCompleteTextView) findViewById(R.id.actv4);
autoText1.setAdapter(arrayAdapter);
autoText1.setThreshold(1);
autoText1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//autoText1.showDropDown();
hideKeyBoard(view);
//String selection = (String) parent.getItemAtPosition(position);
selected = position;
}
});
/*autoText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autoText1.showDropDown(); }
});*/
ImageView imageView = (ImageView) findViewById(R.id.imv1);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autoText1.showDropDown(); }
});
Also You should set-up a String of locnames as in mine in Strings.XML like this:
<string-array name="Loc_names">
<item>India</item>
<item>America</item>
<item>Germany</item>
<item>Russia</item>
<item>Australia</item>
<item>China</item>
</string-array>
The Message part in code of YourActivity.java here shows the same pop-up/spinner by clicking anywhere on the AutoCompleteTextView which removes the need of using an ImageView (arrow) but you want an ImageView that's why I've made this code a message/comment.
/*autoText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autoText1.showDropDown(); }
});*/
As I've directly copied this from my project, you should replace all ids/names according to you.Some images for reference
This is normal AutoCompleteTextView.
This is AutoCompleteTextView with a Spinner.
This is AutoCompleteTextView with some text entered and text
filtered in the spinner.

you can use EditSpinner auto complete spinner lib.
Add it to gradle :
compile 'com.reginald:editspinner:1.0.0'
add the view to your xml file :
<com.reginald.editspinner.EditSpinner
android:id="#+id/autocomplete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:dropDownDrawable="#mipmap/ic_keyboard_arrow_down_black_24dp"
app:dropDownDrawableSpacing="35dp" />
prepare your adapter :
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, itemList);
set adapter to your EditSpinner :
autoCompleteOperationDetail.setAdapter(operationDetailArrayAdapter);

Related

Custom AlertDialog with RecyclerView - list is always empty

First, I created activity with RecyclerView, it works fine. My original code:
activity_agreements.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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:paddingTop="8dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toTopOf="#+id/editText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="#+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:ems="10"
android:gravity="left"
android:inputType="none|text|textPersonName"
android:text="* required fields"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/btnGetSelected"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:id="#+id/btnGetSelected"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginBottom="4dp"
android:text="I agree"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</android.support.constraint.ConstraintLayout>
Agreements list passed to ActivityAgreements and adapter setup:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agreements);
btnGetSelected = findViewById(R.id.btnGetSelected);
list = findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
agreements = getIntent().getParcelableArrayListExtra("agreements");
AgreementsAdapter adapter = new AgreementsAdapter(this.agreements);
list.setAdapter(adapter);
My adapter code:
public class AgreementsAdapter extends RecyclerView.Adapter<AgreementsAdapter.ViewHolder>
{
ArrayList<Agreement> agreements;
public AgreementsAdapter(List<Agreement> agreements)
{
this.agreements = new ArrayList<>(agreements);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.agreement_list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.bindData(agreements.get(position));
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(agreements.get(position).getAccepted());
//holder.checkbox.setFloorUnCheckedColor(agreements.get(position).getRequired()? Color.rgb(255,0,0):Color.rgb(0,255,0) );
holder.checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> agreements.get(holder.getAdapterPosition()).setAccepted(isChecked));
}
#Override
public int getItemCount()
{
return agreements.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder
{
private TextView textAgreementName;
private AppCompatCheckBox checkbox;
public ViewHolder(View v)
{
super(v);
//textAgreementName = v.findViewById(R.id.text_agreement_name);
checkbox = v.findViewById(R.id.checkbox_agreement_accepted);
}
public void bindData(Agreement agreement)
{
//checkbox.setFloorUnCheckedColor(agreement.getRequired()? Color.rgb(255,0,0):Color.rgb(0,0,255) );
/*if(agreement.getRequired())
{
textAgreementName.setTypeface(null, Typeface.BOLD);
textAgreementName.setText(agreement.getName() + " *");
}
else
textAgreementName.setText(agreement.getName());*/
if(agreement.getRequired())
{
checkbox.setText(agreement.getName() + " *");
checkbox.setTypeface(null, Typeface.BOLD);
}
else
{
checkbox.setText(agreement.getName());
}
}
}
}
All is fine, activity with list shows itself without any problems. Now, I want to use AlertDialog, not activity to display agreements list. I'm trying to create AlertDialog this way (in main activity):
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.activity_agreements, null);
alertDialog.setView(convertView);
RecyclerView list = convertView.findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
AgreementsAdapter adapter = new AgreementsAdapter(agreements);
list.setAdapter(adapter);
alertDialog.show();
agreements variable contains agreements list (the same as previously passed to AgrrementsActivity). But it does not work - dialog is shown with custom layout, but list is always empty.
Can anybody point me what am I missing?
New code with fixed size and other suggestions:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.activity_agreements, null);
RecyclerView list = convertView.findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
AgreementsAdapter adapter = new AgreementsAdapter(agreements);
list.setAdapter(adapter);
alertDialog.setView(convertView);
AlertDialog dialog = alertDialog.create();
dialog.getWindow().setLayout(600, 400);
dialog.show();
adapter.notifyDataSetChanged();
Your RecyclerView is probably showing the list, but it has a height of 0 so it looks empty.
Dialog size is kind of tricky, check this answer and try to give it a fixed height (maybe a percent of your screen height).
I know it is very late to answer this question but I have also faced the same issue. So for the people who is still facing this issue can use below technique.
If you are using Recycler View with constraint layout and have set the layout_height="0" in alert dialog then u will not be able to see the recycler View list. to resolve this issue set this
app:layout_constraintHeight_default="wrap"
in recyclerview
after hours looking for the best way to use RecyclerView and AlertDialog and ConstraintLayout, solution:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/abc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/abc" />
<ProgressBar
android:id="#+id/progressBarFavorito"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/abc" />
</androidx.constraintlayout.widget.ConstraintLayout>
for Using recyclerview in alertdialogue,u should be a bit tricky.As u use match parent,so width of recyclerview is 0 because recyclerviews dimension is set before alertdialogue is created.So you do such:
1)use runnable and set your adapter (or other activities we do with recyclerview) 1 sec delaying
or,
2)when you initialize recyclerview,then just set it's layoutparams programmactically. This solved my issue.(don't use this code blindly,i just copied it from my codes,and it may not be suitable for your one.rather just get idea about the issue.)
member_list.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

OnItemClickListener is not firing

I am making an app that has a list of exercises to do displayed in a ListView. I am trying to let the user select an item from the list to start a new activity, but my OnItemClickListener is not firing. Here is my Activity, (not a listActivity, it is appCompatActivity):
ArrayList<Exercise> myExercises = new ArrayList<>();
AlertDialog.Builder alertDialogBuilder;
ArrayAdapter<Exercise> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
refreshList();
Button newExButton = (Button) findViewById(R.id.newExButton);
arrayAdapter = new ArrayAdapter<Exercise>(
this,
android.R.layout.simple_list_item_1,
myExercises );
ListView lv = (ListView) findViewById(R.id.actList);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("listener heard");
// selected item
int selection = position;
startExercise(selection);
}
});
lv.setAdapter(arrayAdapter);
}
public void refreshList(){
setContentView(R.layout.activity_list);
ListView lv = (ListView) findViewById(R.id.actList);
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setAdapter(arrayAdapter);
}
public void startExercise(int selection){
Intent exIntent = new Intent(this, CommenceExercise.class);
Exercise chosenEx = myExercises.get(selection);
Bundle info = new Bundle();
info.putLong("duration", chosenEx.getTime());
info.putString("name", chosenEx.getName());
info.putString("description", chosenEx.getDescription());
exIntent.putExtras(info);
startActivity(exIntent);
}
The list is initially empty, but the user adds items by pressing a button. The button creates an alertDialog through the code below:
public void addNewActivity(View view) {
//get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.custom, null);
alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.exNameInput);
final EditText durInput = (EditText) promptsView
.findViewById(R.id.exDurInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
long duration = 0;
String exName;
exName = userInput.getText().toString();
duration = Integer.valueOf(durInput.getText().toString());
myExercises.add(new Exercise(exName, duration));
// create new exercise with user input
refreshList();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
And here is my xml:
<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"
android:descendantFocusability="blocksDescendants"
tools:context="com.example.mytimer.ListActivity">
<TextView
android:id="#+id/textView2"
android:layout_width="146dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:text="Activities"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="16dp"
android:clickable="false"
android:layout_marginEnd="16dp" />
<Button
android:id="#+id/newExButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="87dp"
android:onClick="addNewActivity"
android:text="New Exercise"
android:textSize="18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<ListView
android:id="#+id/actList"
android:layout_width="328dp"
android:layout_height="301dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/newExButton"
app:layout_constraintVertical_bias="1.0">
<requestFocus/>
</ListView>
<TextView
android:id="#+id/debugText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:clickable="false"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
</android.support.constraint.ConstraintLayout>
When I tap an item I've added to the list, nothing happens. I can tell that the OnItemClickListener is not being fired because the System.out line is never printed. I'm at a loss as to why I can't get it to work. Any help would be greatly appreciated. Thanks in advance.
You need to remove below listview attributes from xml:
android:descendantFocusability="blocksDescendants"
android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="true"
Also, there is no need of refreshList() this is actually bad way of doing things, instead in your addNewActivity(), once your model is ready(probably on click of positive button) add that item to arrayAdapter and then do arrayAdapter.notifyDataSetChanged().
I hope this helps you!
I think problem in XML Please set ListView clickable true
please do some changes in XML
<ListView
android:id="#+id/actList"
android:layout_width="328dp"
android:layout_height="301dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:descendantFocusability="blocksDescendants"
android:focusable="true" // change this
android:clickable="true" // change this
android:focusableInTouchMode="true" // change this
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/newExButton"
app:layout_constraintVertical_bias="1.0">
<requestFocus/>
</ListView>
Change your refreshList method to below one
public void refreshList(){
arrayAdapter.notifyDataSetChanged();
}
What you're doing is, inflating a ListView again and setting new data to it rather than updating old one. And when you assign new value to ListView you forgot to set onClickListener.
It'll work.
That's really strange... your code should have worked... I would suggest you to try implementing the in your activity to include lv.setClcickable(true) and
lv.setEnable(true) :
public class MenuActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
ArrayList<Exercise> myExercises = new ArrayList<>();
AlertDialog.Builder alertDialogBuilder;
ArrayAdapter<Exercise> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
refreshList();
Button newExButton = (Button) findViewById(R.id.newExButton);
arrayAdapter = new ArrayAdapter<Exercise>(
this,
android.R.layout.simple_list_item_1,
myExercises );
ListView lv = (ListView) findViewById(R.id.actList);
lv.setClickable(true);
lv.setEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view , int
position, long id)
{
startExercise(position);
}
lv.setAdapter(arrayAdapter);
}
public void refreshList(){
setContentView(R.layout.activity_list);
ListView lv = (ListView) findViewById(R.id.actList);
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setAdapter(arrayAdapter);
}
public void startExercise(int selection){
Intent exIntent = new Intent(this, CommenceExercise.class);
Exercise chosenEx = myExercises.get(selection);
Bundle info = new Bundle();
info.putLong("duration", chosenEx.getTime());
info.putString("name", chosenEx.getName());
info.putString("description", chosenEx.getDescription());
exIntent.putExtras(info);
startActivity(exIntent);
}
}
or add these three lines to your xml
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="true
android:descendantFocusability="blocksDescendants"
If there are any focusable child views then the first click will always be for focus
And I would Suggest You to use Custom ListView with Viewholder Pattern for efficiency or the Recyclerview of support Library this will make your scroll smooth and won't create extra View Objects... It will only create the View Object that's will fit the screen
Here is the Link for RecyclerView https://guides.codepath.com/android/using-the-recyclerview

how to set text to text view based on the selection of item in dialogfragment and value of text in main activity, is it possible?

Here I am trying to set text to a textview in my activity.
The text is set to the text view based on the text of the text view in my activity and the selected item in the custom dialog fragment.
The dialog fragment consists of recycler view and a button.when item is selected from the fragment and text of textview of my activity, and with both cases settext to the textview. I tried different code but I not getting how to achieve it anyone give me solution for it. is there a way to get it.
by using value of text and selected item, adding my math and condition to it. settext to the textview. I am beginner to coding can any one help me please I'm trying from 5 days to achieve it. please help me thanks in advance
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="YOUR DAILY TARGET"
android:layout_gravity="center"
android:id="#+id/textView7"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_gravity="center"
android:id="#+id/res"
android:layout_marginTop="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select a glass"
android:layout_marginLeft="10dp"
android:id="#+id/textView6"
android:layout_gravity="center" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:src="#android:drawable/ic_input_add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="70dp"
android:layout_height="70dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:background="#drawable/circle"
android:gravity="center"
android:id="#+id/glasses"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="31dp"
android:layout_marginEnd="31dp"
android:layout_marginBottom="121dp" />
</RelativeLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private Listen selectedListen;
protected void setDataFromMyDialog(Listen listen) {
this.selectedListen = listen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, Page.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
TextView textView = (TextView)findViewById(R.id.res);
Intent r = getIntent();
double res = r.getDoubleExtra("res", 0);
textView.setText(+res + "L"); // with this text value
double ram = Double.parseDouble(textView.getText().toString());
TextView gls = (TextView) findViewById(R.id.glasses);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DiaFragment df = new DiaFragment();
df.show(MainActivity.this.getSupportFragmentManager(), "Frag");
}
});
}
with the text of textview above and selected item in my dialog fragment by using both the values the set text of TextView glasses.is it possible to get like this
DiaFrag:
public class DiaFragment extends DialogFragment {
ListAdapter listAdapter;
public DiaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
setCancelable(false);
Button ok = (Button) v.findViewById(R.id.submit);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.list);
listAdapter = new ListAdapter(getContext(),getData());
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setDataFromMyDialog(listAdapter.getSelectedData());
dismiss();
}
});
return v;
}
public static List<Listen> getData()
{
List<Listen> data = new ArrayList<>();
int[] images = {R.drawable.bottle,R.drawable.lotion,R.drawable.soap,R.drawable.soda,R.drawable.sodaa};
String[] texts = {"250ml","300ml","500ml","750ml","1ltr"};
for (int i=0;i<texts.length && i<images.length;i++){
Listen current = new Listen();
current.img = images[i];
current.text= texts[i];
data.add(current);
}
return data;
}
}

Create a ListView with selectable rows/change background color of ListView rows when clicked

Problem
I'm trying to create a ListView with selectable items. I want to be able to click on an item in the ListView and have the item change color in the list, and then go on and do something else with the data from the row.
I'm using a SimpleAdapter.
How do I make it so that when I tap on a row, it turns a different color, and then when I tap on a different row, the new row is selected and changed to a new color, and the old row changes back to normal?
Code
Here is my code so far. The DBTools class is has all of the data that I want to be displayed in my ListView organized and taken care of. The getAllReceivers() method returns an ArrayList of HashMap<String, String>s that have all of my data.
MainActivity.java:
public class MainActivity extends ListActivity {
DBTools dbTools = new DBTools(this);
ArrayList<HashMap<String, String>> receiverList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
receiverList = dbTools.getAllReceivers();
dbTools.close();
ListView listView = getListView();
if(receiverList.size() != 0) {
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] {"receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath});
setListAdapter(adapter);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="My List" />
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:id="#android:id/list" />
</TableLayout>
receiver_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tableRow" >
<TextView
android:id="#+id/receiverId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/receiverName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Robotronics" />
<TextView
android:id="#+id/fullPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123.45.678.910:8088/robtrox/find" />
</TableRow>
Solution
The solution to this problem is very simple. We need to add an OnItemClickListener to our ListView to listen for clicks and respond accordingly.
So, in the onCreate() method, once you've made sure that you set of data isn't empty, you're going to want to Override the onItemClick() method to listen for the click and change the color. You're also going to want to keep track of which item you selected for the later steps, so add public int selectionId = -1; at the top of your class. Furthermore, you'll need to let the ListAdapter know that you changed something by calling ((SimpleAdapter) getListAdapter()).notifyDataSetChanged().
if(receiverList.size() != 0) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
view.setBackgroundColor(Color.RED);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
});
SimpleAdapter adapter = getNewAdapter();
setListAdapter(adapter);
}
Great! Now we have a working system that will change the color of the row that you tap. But we're not done yet. We need to make sure that the previous selection changes back to the normal color.
For this, we are going to use override the SimpleAdapter's getView() method, which is called everytime the ListView goes to draw the items being displayed in it.
It only actually displays the items it needs to - the ones that you can see. It does not render the ones above or below your screen. So if you have 200 items in a ListView, only 5 or 6, depending on the size of your screen and the size of the items, are being rendered at a time.
To override the getView() method, go up to where you initialize the adapter and change the code to this:
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
Every time one of the rows is drawn, since the getView() will get called, the ListView will check if the current view has the id of row you selected. If it doesn't, it'll change the background color to white. If it does, it'll change the background color to red.
And voila! That's it! Now you are setting the background color to red when you click on an item in the ListView.
Final Code
MainActivity.java:
public class MainActivity extends ListActivity {
DBTools dbTools = new DBTools(this);
ArrayList<HashMap<String, String>> receiverList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
receiverList = dbTools.getAllReceivers();
dbTools.close();
ListView listView = getListView();
if(receiverList.size() != 0) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
view.setBackgroundColor(Color.RED);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
});
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
setListAdapter(adapter);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="My List" />
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:id="#android:id/list" />
</TableLayout>
receiver_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tableRow" >
<TextView
android:id="#+id/receiverId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/receiverName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Robotronics" />
<TextView
android:id="#+id/fullPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123.45.678.910:8088/robtrox/find" />
</TableRow>

Androids ExpandableListView - where to put the button listener for buttons that are children

I have been playing around a lot with the ExpandableListView and I cannot figure out where to add the button listeners for the button that will be the children in the view. I did manage to get a button listener working that uses getChildView() below, but it seems to be the same listener for all the buttons.
The best case scenario is that I would be able to implement the button listeners in the class that instantiates the ExpandableListAdapter class, and not have to put the listeners in the actual ExpandableListAdapter class. At this point I don't even know if that is possible
I have been experimenting with this tutorial/code: HERE
getChildView()
#Override
public View getChildView(int set_new, int child_position, boolean view, View view1, ViewGroup view_group1)
{
ChildHolder childHolder;
if (view1 == null)
{
view1 = LayoutInflater.from(info_context).inflate(R.layout.list_group_item_lv, null);
childHolder = new ChildHolder();
childHolder.section_btn = (Button)view1.findViewById(R.id.item_title);
view1.setTag(childHolder);
childHolder.section_btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(info_context, "button pushed", Toast.LENGTH_SHORT).show();
}
});
}else {
childHolder = (ChildHolder) view1.getTag();
}
childHolder.section_btn.setText(children_collection.get(set_new).GroupItemCollection.get(child_position).section);
Typeface tf = Typeface.createFromAsset(info_context.getAssets(), "fonts/AGENCYR.TTF");
childHolder.section_btn.setTypeface(tf);
return view1;
}
Any help would be much appreciated. Thank you and I will be standing by.
If the buttons are in the ExpandableListView, their listener needs to be in the adapter.
I'm not sure the thrust of your question, but if you are asking how do you relate the button to the contents of the child row, I can answer that. :p
I'll assume a somewhat simple child row layout for demonstration purposes.
child_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/ListItem1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="7dip"
android:paddingRight="7dip"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/ListItem2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Then, to get the contents of the row when your button is pressed, you use the button to backtrack to the parent vieew and then get the necessary child views and their contents:
childHolder.section_btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
LinearLayout ll = (LinearLayout) v.getParent(); // get the view containing the button
TextView tv1 = (TextView) ll.findViewById(R.id.ListItem1); // get the reference to the first widget
TextView tv2 = (TextView) ll.findViewById(R.id.ListItem2); // get the reference to the second widget
String text1 = tv1.getText.toString(); // Get the contents of the first widget to a string
String text2 = tv2.getText.toString(); // Get the contents of the second widget to a string
}
});
If this isn't what you were looking for clarify your question and I'll take another shot at it.

Categories