How can I add different ids to buttons recyclerview - java

My project is based on a recycler view. The layout of each elements is this :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imgview"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="2dp" />
<TextView
android:id="#+id/txtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="51dp"
android:layout_marginTop="1dp"
android:text="Line 1"
android:textColor="#android:color/black"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="52dp"
android:layout_marginTop="29dp"
android:layout_marginBottom="1dp"
android:text="Line 2"
android:textSize="15sp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:text="Voir plus" />
</RelativeLayout>
And I edit it with this :
ArrayList<exempleitem> ExampleList = new ArrayList<>();
ExampleList.add(new exempleitem(R.drawable.ic_android, "Line 1", "Line 2 ", button2.setId(R.id.hydro) ));
ExampleList.add(new exempleitem(R.drawable.ic_baseline_airplanemode_active_24, "Line 3", "Line 4 ",button3.setId(R.id.hel)));
ExampleList.add(new exempleitem(R.drawable.ic_baseline_beach_access_24, "Line 5", "Line 6 ",button4.setId(R.id.lit)));
My problem is that I would like to change the ID of each button, and it doesnt work.
I can't think of anything else right now, and I'm quite a begginner.

I think you don't know how a recyclerview works. It doesn't matter if a button have the same id as another as long as they live in different "cells". Thats the purpose of recyclerviews.
So you have to create a recyclerview adapter and put all the logic in there, the logic will be based on a dataset which is an array probably and your clicks will be based on the position of that array.
You can read more from Google's official guide
Hope it helps!

You shouldn't change the ids and if I am not mistaken, you are not even allowed to do that.
I read in the comments that you want to change the event of a button. Try encapsulating the actions of each button click into methods and then setOnClickListener again on the buttons to change their on click action.
Initial Code before changing action
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dosmthA();
}
});
To change action simply:
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dosmthB();
}
});
You can even create View.OnClickListener() objects and interchange them in the setOnClickListener() method like so:
View.OnClickListener action = new View.OnClickListener() {
#Override
public void onClick(View view) {
smth();
}
}
view.findViewById(R.id.button_first).setOnClickListener(action);

You can use a ViewHolder and RecyclerView Adapter to set Click listener for each view...
If you share me the adapter code snippet I can give you the code...
😁

Related

onClick method not working in android studio

I made a side navigation drawer and it works fine but whenever I click any option in navigation drawer nothing happens.It's like it is not taking any input. Onclicking any option I want to redirect user to a new activity but unfortunately it doesn't happens.
XML code is as follows
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="ClickTournament_info"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tournament Info"
android:padding="12dp"
android:layout_marginStart="16dp"/>
<ImageView
android:layout_marginTop="-10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="48dp"
android:src="#drawable/tournament_info"/>
</LinearLayout>
Java code is as follows
public void ClickTournament_info(View view){
redirectActivity(this,TournamentInfo.class);
}
public static void redirectActivity(Activity activity,Class aClass) {
//Initialize intent
Intent intent = new Intent(activity,aClass);
//set flag
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//start activity
activity.startActivity(intent);
}
I think you need to use the onNavigationItemSelected method when you want to handle click events on the navigation drawer.
Learn more: https://developer.android.com/reference/com/google/android/material/navigation/NavigationView.OnNavigationItemSelectedListener#onNavigationItemSelected(android.view.MenuItem)
Firstly, try to always create an Onclicklistener instead of adding an onclick attribute in xml.
In your xml, add an ID attribute to your linear layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearlayout"
android:orientation="horizontal"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="ClickTournament_info"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tournament Info"
android:padding="12dp"
android:layout_marginStart="16dp"/>
<ImageView
android:layout_marginTop="-10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="48dp"
android:src="#drawable/tournament_info"/>
</LinearLayout>
Now in your classfile inside the Oncreate Method,
LinearLayout LinearLayout = (LinearLayout )findViewById(R.id.linearlayout);
LinearLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
redirectActivity(this,TournamentInfo.class);
}
});
You already have an onClick method. start navigating from that method only.
Try like this,

Android button not clickable when turning visible

Hi Im posting this after not finding any possible answer here.
I have an invisible LinearLayout LL1 in a fragment that I turn visible when a recylerView data is empty, that LL1 has a button on it. The problem is simply that the button is not clickable ! I tried setting the listener in different ways but still not working. Here's the code below:
Here's the xml file:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.main.MainActivity"
android:layout_marginTop="3dp">
<LinearLayout
android:id="#+id/msg_emty_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_empty_box" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aucune vente n'a été trouvée !"
android:textSize="15dp"
android:layout_gravity="center_horizontal"
android:textColor="#color/greydark"/>
<Button
android:id="#+id/btnAddSale"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Créer une vente"
android:textColor="#color/whiteTextColor"
android:background="#drawable/centre_button">
</Button>
</LinearLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_db"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_sale_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_add_db"
android:layout_margin="20dp"
android:layout_gravity="bottom|end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccesGreen"
android:src="#drawable/ic_edit"/>
</android.support.design.widget.CoordinatorLayout>
And here's the java:
private void generateSaleList(ArrayList<Sale> saleArrayList, View view) {
if(saleArrayList.isEmpty()){
getActivity().setTitle("Ventes sur portable");
msgLayout.setVisibility(View.VISIBLE);
creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
creatSaleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Button clicked !", Toast.LENGTH_LONG).show();
}
});
creatSaleBtn.setClickable(true);
}else{
msgLayout.setVisibility(View.GONE);
recyclerView_db = view.findViewById(R.id.recycler_view_sale_list);
adapter_db = new SaleAdapter((ArrayList<Sale>) Utils.sortArray(saleArrayList),this,1,getContext(),this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView_db.setLayoutManager(layoutManager);
recyclerView_db.setAdapter(adapter_db);
adapter_db.notifyDataSetChanged();
}
}
Do you guys see what's causing this weird problem ?
You can try with requestFocusFromTouch()
Call this to try to give focus to a specific view or to one of its
descendants.
msgLayout.setVisibility(View.VISIBLE);
creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
creatSaleBtn.requestFocusFromTouch();
Hide your RecyclerView when there's no items (set visibility to gone). The problem is that it's capturing the clicks, since it's placed on top of the button.
as u said in comments you not using creatSaleBtn.setClickable(false); anywhere, then you have to hide the recyclerView using recyclerView_db.setVisibility(View.GONE);
why? because it by default fits the full-screen due too match_parent for width and height.
please add recyclerView_db.setVisibility(View.GONE); in the saleArrayList.isEmpty() check
so your new code will be :
if(saleArrayList.isEmpty()){
recyclerView_db.setVisibility(View.GONE);
getActivity().setTitle("Ventes sur portable");
msgLayout.setVisibility(View.VISIBLE);
creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
creatSaleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Button clicked !", Toast.LENGTH_LONG).show();
}
});
creatSaleBtn.setClickable(true);
}
SwipeRefreshLayout's visibility should be GONE after recyclerview is empty.
of coarse recyclcerview is empty but it is still visible so your click events are caught by SwipeRefreshLayout witch is defined on top of LL1.
EDIT
instead of recyclerview, set swipe_refresh_db visibility to gone cos I doubt recyclerview is a child of swipe_refresh_dd so if you set recyclerview's visibility to gone, swipe_refresh_db is still visible and gets click events.
give it a try

How to change a layout in same activity by clicking a Button?

Change a layout in same Activity when click on play button then layout show pause Button at the same place in Android Studio music player app.
How it is possible?
I'm a beginner so I don't know how to use method about it?
I cannot get an answer.
I understand from your question that when your user taps pause button, you should hide pause button and show play button and vice-versa. This is relatively simple to achieve. Just create a layout with a linear layout with two buttons like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal"
android:padding="5dp">
<Button
android:id="#+id/btnPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:layout_weight="1"
android:text="Play"
android:padding="5dp"/>
<Button
android:id="#+id/btnPause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:text="Pause"/>
</LinearLayout>
Now set on click listner to both of the buttons and handle button visibility within that like this :
Button btnPlay = barcodeDialog.findViewById(R.id.btnPlay);
Button btnPause = barcodeDialog.findViewById(R.id.btnPause);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPlay.setVisibility(View.GONE);
btnPause.setVisibility(View.VISIBLE);
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPlay.setVisibility(View.VISIBLE);
btnPause.setVisibility(View.GONE);
}
});
This way you can handle the visibility of your Play and Pause buttons. Reply if you need more information.

Button setOnClickListener is not working only for one button

I have two different buttons in my activity, and an if statement to show them...
My if statement is working well and show the right button, but one of those buttons is not doing anything when I click on it! (Actually, it's not clickable at all!)
if (isNeeded)
{
// buttonImportant is not clickable
buttonImportant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG", "Clicked!"); // Even this log won't work!
Intent intentDetailsActivity = new Intent(MainActivity.this, DetailsActivity.class);
intentDetailsActivity.putExtra("extraPosition", String.valueOf(position));
startActivity(intentDetailsActivity);
}
});
linearLayoutImportant.setVisibility(View.VISIBLE); // This line is working
}
if (!isNeeded)
{
// buttonNormal is working well!
buttonNormal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutNormal.setVisibility(View.GONE);
Intent intentDetailsActivity = new Intent(MainActivity.this, DetailsActivity.class);
intentDetailsActivity.putExtra("extraPosition", String.valueOf(position));
startActivity(intentDetailsActivity);
}
});
linearLayoutNormal.setVisibility(View.VISIBLE); // And this one is not working too!
}
The problem is, it won't return any error or log, to know what's the problem! It's log I disabled the button... (which I didn't)
I checked if it's for declarations, but everything is declared well...
I checked the XML, there's no problem there either:
<LinearLayout
android:id="#+id/linearLayoutImportant"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:layout_centerInParent="true"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:visibility="gone" >
<TextView
android:id="#+id/textViewImportant"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="#string/important"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<Button
android:id="#+id/buttonImportant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/details" />
</LinearLayout>
...
...
<LinearLayout
android:id="#+id/linearLayoutNormal"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="25dp"
android:orientation="vertical"
android:visibility="gone" >
<Button
android:id="#+id/buttonClose"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="end"
android:background="#android:drawable/ic_menu_close_clear_cancel" />
<TextView
android:id="#+id/textViewNormal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:text="#string/normal"
android:textStyle="bold" />
<Button
android:id="#+id/buttonNormal"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_margin="2dp"
android:layout_gravity="center_horizontal"
android:text="#string/details" />
</LinearLayout>
EDIT:
Here's the declarations:
LinearLayout linearLayoutImportant, linearLayoutNormal;
Button buttonImportant, buttonClose, buttonNormal;
...
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayoutImportant = (LinearLayout) findViewById(R.id.linearLayoutImportant );
buttonImportant = (Button) findViewById(R.id.buttonImportant);
buttonClose = (Button) findViewById(R.id.buttonClose);
buttonClose .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutNormal.setVisibility(View.GONE);
}
});
buttonNormal = (Button) findViewById(R.id.buttonNormal);
linearLayoutNormal = (LinearLayout) findViewById(R.id.linearLayoutNormal);
}
EDIT 2:
Alright guys, maybe I didn't made it clear...
That isNeeded is a variable and I control it from another place...
When I make it false, the second if will get executed very well, and when I make it true, the first if will execute too, but only the button is not clickable!
EDIT 3:
I also checked .setEnabled(true); or .setClickable(true);, still not working... :/
SOLVED:
I used the HierarchyViewer and found the problem. The problem was in XML... I had a ListView on top of second button, but it was empty, so I thought nothing's there...
Sorry everybody...
I used the HierarchyViewer and found the problem. The problem was in XML... I had a ListView on top of second button, but it was empty, so I thought nothing's there...
Sorry everybody...
Try without the if statement in order to know if is a validation problem and you're only setting one listener
The boolean variable isNeeded can take only one of the two values, either true or false. Therefore only one of the if conditions will be executed.
Since only one of the condition is true, you are only setting an onClickListener to one of the buttons and thus the other button won't be clickable and the log message within the onClick method won't be visible in the logs.
Hope this answered your question.
All the best :)
set isNeeded = true before
if (isNeeded)
{
// buttonImportant is not clickable
buttonImportant.setOnClickListener(new View.OnClickListener() {
then test it again.
Good lucky!
There was an error posting my ans so i have taken a screenshot of it. Please review it for your answer

Programmatically adding a TextView onto an existing XML file

My main screen displays info from user input.
Now everything on this screen is added using XML apart from "Kool" TextView on the top left corner. Now I want a way to get info from a user and add it underneath the first row of information.
I've sorted out the screen that gets user input the problem is actually getting the layout perfect. Now I added "Kool" TextView programmatically but the layout is wrong.
How can I make it so it so the "Kool" TextView is underneath the date "20/08/15". Every time I use the setHeight method it makes the TextView invisible.
Code:
public class AnalysisPage extends Activity {
Button savebutton,cancelbutton;
EditText dateinput,weightinput,repsinput;
int dd,mm,yy;
private TextView texty = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dumbbellpress);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.addinfo:
Dialog dialog = new Dialog(AnalysisPage.this);
dialog.setTitle(" Enter your STATS brah");
dialog.setContentView(R.layout.datainput);
dateinput = (EditText)dialog.findViewById(R.id.editDate);
final Calendar c = Calendar.getInstance();
dd = c.get(Calendar.DAY_OF_MONTH);
mm = c.get(Calendar.MONTH);
yy = c.get(Calendar.YEAR);
dateinput.setText(new StringBuilder().append(dd).append("/").append(mm+1).append("/").append(yy));
dialog.show();
weightinput = (EditText)dialog.findViewById(R.id.editWeight);
repsinput = (EditText)dialog.findViewById(R.id.editReps);
savebutton = (Button)dialog.findViewById(R.id.btnSave);
cancelbutton = (Button)dialog.findViewById(R.id.btnCancel);
savebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RelativeLayout views = (RelativeLayout)findViewById(R.id.xxx);
texty = new TextView(AnalysisPage.this);
texty.setTextSize(28);
texty.setText("Kool");
views.addView(texty);
}
});
cancelbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="1" android:id="#+id/statslayout">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/xxx">
<TableRow
android:layout_width="fill_parent"
android:layout_height="100dp" android:id="#+id/tableRow3" android:layout_alignParentTop="true"
android:layout_alignParentStart="true" android:layout_marginStart="72dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Dumbbell Press Stats!"
android:id="#+id/textView"/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="100dp" android:id="#+id/tableRow"
android:layout_alignParentTop="true" android:layout_alignEnd="#+id/tableRow3"
android:layout_marginTop="49dp" android:layout_alignBottom="#+id/tableRow3">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Date"
android:layout_weight="0.22"
android:id="#+id/btnDate"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=" Weight"
android:layout_weight="0.22"
android:id="#+id/txtWeight"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=" Reps"
android:layout_weight="0.22"
android:id="#+id/btnReps"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_below="#+id/tableRow" android:layout_alignParentStart="true" android:id="#+id/tableRow4">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="20/08/15"
android:id="#+id/textView2" android:layout_below="#+id/tableRow"
android:layout_alignStart="#+id/tableRow3"/>
</TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=" 8"
android:id="#+id/textView7"
android:layout_marginEnd="82dp" android:layout_below="#+id/tableRow"
android:layout_alignEnd="#+id/tableRow3"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="50kg"
android:id="#+id/textView6"
android:layout_marginStart="43dp"
android:layout_below="#+id/tableRow3" android:layout_toEndOf="#+id/tableRow4"/>
</RelativeLayout>
My end (dream) goal for this is by using Java I making complete perfectly formatted rows which contains the Date, Weight and Reps in their respected columns. And multiple rows of this or perfectly formatted using Java.
Image (this is in XML not in Java)
Rather than add TextView(s) programmatically, use a ListView. This will solve your problems entirely. You would use a custom adapter setAdapter() that your ListView would set as it's adapter (that provides the List it's data), and add new row elements each time you click your button that adds the new items. This would mean replacing your TableRow bit, and using a ListView in the RelativeLayout instead. Also, you could add a custom header view to the ListView to replace that header you already use (source: addHeaderView() )
Looking at your rows, it appears that they have the fields: "Date", "weight" and "reps". This would mean create a custom Java object that has those three fields, and make the the object type of your ListView adapter's elements. I can provide starter code if you REALLY need it, but it would help you best to use the documentation I provided to teach your self how to use the ListView.
Tutorial: ListView tutorial
Edit: Another bonus: ListView handles allowing the user to scroll as more, and more rows are added to this List of yours. More reason to just opt to a ListView :)

Categories

Resources