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
Related
I am new to using Java and Android Studio and I'm stumped. I have created an application with bottom navigation and that functions fine. I'm trying to use a floating action button to create list entries into a ListView. I've created an adapter for the ListView and an XML for it but when I actually click on the tab, nothing shows up. I think the issue may lie in using onCreate vs. onCreateView, but since I'm new I'm not really sure what I should put where. As my code stands, the fragment loads with nothing showing except for the title of the fragment. I stopped using onCreateView and put everything under onCreate because my fragment was crashing. Any help would be appreciated.
Fragment Java:
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
private FragmentDashboardBinding binding;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView ListView;
EditText editText;
public String test;
public void onCreate(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText = (EditText) getView().findViewById(R.id.editText);
listItems = new ArrayList<String>();
listItems.add("Let's see where this ends up");
ListView = (ListView) getView().findViewById(R.id.ListView);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
ListView.setAdapter(adapter);
binding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fab:
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
}
}
);
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT)
.show();
}
});
dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textDashboard;
dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}}
Fragment XML:
<TextView
android:id="#+id/textview_first8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="153dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="154dp"
android:text="#string/title_dashboard"
android:textColor="#color/teal_font"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="invisible"/>
<ListView
android:id="#+id/ListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="#+id/textview_first8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/text_dashboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="invisible"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="32dp"
android:layout_marginBottom="88dp"
android:clickable="true"
android:src="#android:drawable/ic_menu_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
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));
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);
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;
}
}
This question already has answers here:
Android : How to set onClick event for Button in List item of ListView
(10 answers)
Closed 6 years ago.
I would like to set onclick event for Button in list item of ListView
I have a layout ("list_item.xml") in this way:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow android:layout_width="fill_parent"
android:id="#+id/TableRow_list_item"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:layout_width="0dp"
android:layout_height="80dp"
android:id="#+id/imageView_logo_utente"
android:src="#drawable/icon_user_green"
android:layout_column="1"
android:layout_weight="1"/>
<TextView
android:textColor="#000000"
android:id="#+id/nomec"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Nome Completo"
android:layout_weight="2"
android:gravity="center"
android:height="40dp"
android:textSize="17dp"
android:layout_column="1"/>
<TextView
android:textColor="#000000"
android:id="#+id/tiposogget"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Tipo Soggetto Etichetta"
android:layout_weight="2"
android:gravity="center"
android:height="40dp"
android:textSize="17dp"
android:layout_column="1"/>
<TextView
android:textColor="#000000"
android:id="#+id/cf"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Codice Fiscale"
android:gravity="center"
android:height="40dp"
android:textSize="17dp"
android:layout_column="1"
android:layout_weight="2" />
<TextView
android:textColor="#000000"
android:id="#+id/idsogg"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="ID Soggetto"
android:layout_weight="1"
android:gravity="center"
android:height="40dp"
android:textSize="17dp"
android:layout_column="1"/>
<Button
android:layout_width="0dp"
android:layout_height="90dp"
android:id="#+id/button_scan"
android:layout_column="1"
android:layout_weight="0.63"
android:height="140dp"
android:background="#drawable/custom_button_scanner" />
</TableRow>
And I have a Activity in this way:
public class ActivityListview extends AppCompatActivity {
//************VARIABILI GLOBALI*************
ListView lv;
static final String KEY_CF = "CodiceFiscale";
static final String KEY_ID = "IDSoggetto";
static final String KEY_NOMEC = "NomeCompleto";
static final String KEY_TIPOSOGGET = "TipoSoggettoEtichetta";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_scanner);
lv = (ListView) findViewById(R.id.listView_resultXML);
Example();
}
public void Example() {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[]{KEY_CF, KEY_ID, KEY_NOMEC, KEY_TIPOSOGGET}, new int[]{
R.id.cf, R.id.idsogg, R.id.nomec, R.id.tiposogget});
// selecting single ListView item
ViewGroup headerview = (ViewGroup) getLayoutInflater().inflate(R.layout.header_listview, lv, false);
lv.setAdapter(null);
lv.addHeaderView(headerview);
lv.setAdapter(adapter);
// HERE I WOULD LIKE TO SET ONCLICK BUTTON
// listening to single listitem click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//Metodo per prelevare dati al click sulla casella della ListView
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String st_cf = ((TextView) view.findViewById(R.id.cf)).getText().toString();
//String st_cognome = ((TextView) view.findViewById(R.id.cognome)).getText().toString();
//String st_eliminato = ((TextView) view.findViewById(R.id.eliminato)).getText().toString();
// String st_esterno = ((TextView) view.findViewById(R.id.esterno)).getText().toString();
String st_idsogg = ((TextView) view.findViewById(R.id.idsogg)).getText().toString();
//String st_nome = ((TextView) view.findViewById(R.id.nome)).getText().toString();
String st_nomec = ((TextView) view.findViewById(R.id.nomec)).getText().toString();
//String st_tiposogg = ((TextView) view.findViewById(R.id.tiposogg)).getText().toString();
String st_tiposogget = ((TextView) view.findViewById(R.id.tiposogget)).getText().toString();
Toast.makeText(ActivityListview.this, "Example onclick", Toast.LENGTH_LONG).show();
}
});
}
}
How to set onClick event for Button in list item in Activity?
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.puzzles_row, null);
}
ListedPuzzle lp = items.get(position);
if (lp != null) {
TextView title = (TextView) v.findViewById(R.id.listTitles);
//set as the tag the position parameter
title.setTag(new Integer(position));
title.setOnclickListener(new OnCLickListener(){
#Override
public void onClick(View v) {
// Do the stuff you want for the case when the row TextView is clicked
// you may want to set as the tag for the TextView the position paremeter of the `getView` method and then retrieve it here
Integer realPosition = (Integer) v.getTag();
// using realPosition , now you know the row where this TextView was clicked
}
});
title.setText(lp.getTitle());
CheckBox star = (CheckBox) v.findViewById(R.id.star_listed);
star.setChecked(lp.isStarred());
}
return v;
}
Take above example as modify it
One possibility: You could set the listener in your custom adapter, then create an interface you call when the button is clicked.