How can I display a Toast messages for the items I've chosen in my layout?
For example, I have 15 ImageViews that are selectable, for example I've selected ImageViews 1, 2 and 3. A toast will appear when I click a button, "You've chosen ImageViews 1, 2, 3."
By the way, I've used setTag to know when an ImageView is selected. I've setup setTag("1") for the views that is selected and setTag("0") for the rest.
Sample code that I've tried:
public void onClick(View v) {
String message = "You've chosen";
if (v.getTag().toString().equals("1")) {
message = message + " " + ivCircles[i].getId();
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
finish();
}
This line should be in onClick method of ImageView
message = message + " " + view.getId();
This line should be a global variable
public static String message = "You've chosen";
After toast displayed in onClick method of the button, the global varibale should be initiated again
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
message = "You've chosen";
set contentDescription for each image & after selecting one of the image get content discription
Toast.makeText(context,imageview.getContentDiscription(),Toast.LENGTH_SHORT).show();
You need to use the ActionMode class.
Try this way,hope this will help you to solve your problem.
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/lnrItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
MainActivity.java
public class MainActivity extends Activity {
private LinearLayout lnrItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrItems = (LinearLayout) findViewById(R.id.lnrItems);
for (int i=1;i<=15;i++){
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setTag(String.valueOf(i));
imageView.setImageResource(R.drawable.ic_launcher);
imageView.setAdjustViewBounds(true);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You've chosen ImageViews "+v.getTag().toString(),Toast.LENGTH_SHORT).show();
}
});
lnrItems.addView(imageView);
}
}
}
Related
After login, I want to change text in TextView near profile on name_user.
But it doesn't change textView visually.
It is worth to mention, that when outputting (Toast), it gives out the data that is needed, but does not visually display it. Everything is fine with the TextView parameters (I think), because if you set the finished text in the parameters( i mean android:text="smth"), it visually displays it.
Java code:
`protected void onCreate(Bundle savedInstanceState) {
yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);
DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
Toast toast = Toast.makeText(getApplicationContext(), profileName.getText().toString(),
Toast.LENGTH_SHORT); // for debug, it works and show profileName that contains name_user, but.
toast.show();
findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}`
Part of main XML
`<com.google.android.material.navigation.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/layout_navigation_header"// layour_navigation_header -here is TextView
app:menu='#menu/navigation_menu'
android:layout_gravity="start"/>`
Part of layour_navigation_header with TextView that I need to change.
`<TextView
android:id="#+id/profName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="#color/black"
android:textSize="18sp"
android:text="Temporary"
app:layout_constraintBottom_toTopOf="#id/viewSupporter"
app:layout_constraintStart_toEndOf="#id/imageProfile"/>`
Hope you could help me
I tried to move
`yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change`
before
`super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);`
but final result remains the same. It contains data, but not visually displays it.
You're inflating layout_navigation_header layout and setting a value in one of its textviews. But you never seem to place the layout on screen, the layout instance simply gets discarded.
What gets displayed is the activity_menu2 layout you inflate and set as content view with setContentView(). If that layout includes layout_navigation_header or its look-a-like with some mechanism, it's not the same instance you inflated earlier.
To solve the issue, just call setContentView() to set your desired layout, call findViewById() to find the textview and set a text to it.
I have a button and in XML it looks like this:
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:tag="Greeting"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
Also, I have the method public void onClick(View view) {}. So whenever I click on that button, that method should run. Well, that works fine.
Now, I would like to add dynamic buttons.
if (_layout == R.layout.fragment_general) {
LinearLayout layout = view.findViewById(R.id.root);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for(String text : readFromSharedPreferences(getContext())) {
Button btn = new Button(this.getContext());
btn.setText(text);
btn.setTag(text);
btn.setTextColor(Color.BLUE);
btn.setBackgroundColor(Color.RED);
layout.addView(btn);
}
}
}
The buttons will be added but when I click on them, nothing happens.
I have also tried it with btn.performClick() and btn.callOnClick() but none of them works. In those methods I am missing a parameter. So it should be btn.performClick("onClick") or btn.callOnClick("onClick"). However, I should be able to tell that the method onClick should be executed when I click on a dynamic button. How can I do this?
try this code :-
if (_layout == R.layout.fragment_general) {
LinearLayout layout = view.findViewById(R.id.root);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (String text : readFromSharedPreferences(getContext())) {
Button btn = new Button(this.getContext());
btn.setText(text);
btn.setTag(text);
btn.setTextColor(Color.BLUE);
btn.setBackgroundColor(Color.RED);
layout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
}
you just simply have to add setOnClickListener after btn added to linear layout.
it's working for me
Just started learning Java for application development through Android Studio. Creating an application that collects the user's inputs of which include their Name and Age of which when a Submition button is clicked the output is a string based on their Age range. code below:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Action to the Button
Button BtnSubmit = findViewById(R.id.BtnSubmit);
BtnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TbName = "";
int TbAge =0;
String TxtOuput;
if (TbAge>0 && TbAge<=18)
{
TxtOuput = TbName + ("You Are Still A Child");
}
else if(TbAge>18 && TbAge<=64)
{
TxtOuput = TbName + ("You Are Grown");
}
else if(TbAge>64)
{
TxtOuput = TbName + ("You Are About To Die") + ("R.I.P");
}
}
});
}
}
Tried various methods from google, youtube and other sources but the application will not still execute an output.
Application layout/blueprint:
You are not getting your text fields values in a variable anywhere in code you have shared. Similarly you are not setting those values back to Status text field as well.
So it should be something like this:
If I assume you have firstEditText EditText View for name, secondEditText for age, and resultTextView for status, then your code would be something like below:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Action to the Button
Button BtnSubmit = (Button)findViewById(R.id.BtnSubmit);
EditText firstEditText = (EditText) findViewById(R.id.firstEditText);
EditText secondEditText = (EditText) findViewById(R.id.secondEditText);
TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
BtnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TbName = firstEditText.getText();
int TbAge = Integer.parseInt(secondEditText.getText().toString());
String TxtOuput;
if (TbAge>0 && TbAge<=18)
{
TxtOuput = TbName + ("You Are Still A Child");
}
else if(TbAge>18 && TbAge<=64)
{
TxtOuput = TbName + ("You Are Grown");
}
else if(TbAge>64)
{
TxtOuput = TbName + ("You Are About To Die") + ("R.I.P");
}
resultTextView.setText(TxtOuput);
}
});
}
}
Try this and let me know
AS per your question, you want user to add his name and age in the editText fields. When clicked on SUBMIT button, that entered data should be displayed on the next screen(activity).
To achieve this:
use 2 editText fields and 1 button in your xml layout file.
Problem:
You have added only button view in your layout file and not the editText.
Let me know if you want the code for the same then.
Best and easy way of using onclick listener,
In your xml layout,
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onclick="goToMethod"/>
</LinearLayout>
In your activity,
class MainActivity extends Activity{
public void goToMethod(View view){
//do your code here
}
}
Note: In tools:context you should mention the activity where you are using layout and onclick
I have an activity with RecyclerView and each item in the list looks like below. The star should be clickable and when the user clicks it, it is expected to be changed to dark star. If the use clicks on the list item, it enters a new activity, where further details are provided corresponding to the list item selected. :
This is the XML of list item.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="#drawable/background_state_drawable"
android:clickable="true"
>
<ImageView
android:id="#+id/im_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:src="#mipmap/ic_tonality_black_36dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/lbl_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/im_item_icon"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Sois comme l'eau mon ami"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/lbl_item_sub_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lbl_item_text"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Mononc' J"
android:textSize="14sp" />
<ImageView
android:id="#+id/im_item_icon_secondary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="16dp"
android:src="#mipmap/ic_star_border_black_24dp"
android:background="#drawable/background_state_drawable"
/>
</RelativeLayout>
A nested class in Adapter handles the click events for me.
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("RecyclerView","Item with id : " + v.getId() + " touched");
if(v.getId() == R.id.cont_item_root)
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition()); //not able to come here
}
}
}
I am able to enter the first part of if, i.e. I am able to receive the click event of listItem click. However, when the user clicks star, it is also treated as if the whole list item is clicked as the star lies inside the container.
How can I receive the click on star seperately, so that the click on star is not treated as the click on list item?
EDIT
Adding the line android:descendantFocusability="blocksDescendants" in the RelativeLayout of list item fixed the issue. But can anyone please explain how it fixed it. By name, it is expected to block the descendants and eat the click events. However, the behaviour is opposite.
Since you just want to get the click of the star, you should set the OnClickListener just for the star:
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
secondaryIcon.setOnClickListener(this);
}
reverse the if / else statement and add a click listener for the star image. It should work since you want to trigger the listener for the recyclerview item if the star is not clicked
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
secondaryIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("RecyclerView","Item with id : " + v.getId() + " touched");
if(v.getId() == R.id.im_item_icon_secondary)
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
Hope this helps
You forgot to add onClick listener to secondaryIcon.
Try this:
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
secondaryIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == secondaryIcon.getId())
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
Hope this will help~
You can also declare onclick item for specific views's of row like below in recycler adapter class.
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.linRootMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your stuff here.
}
});
holder.imgStart.setOnClickListner(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your stuff here.
}
});
}
I hope this will help you.
I have just started with developing apps in android, but when I am trying to create an email intent I am getting an error. The file crashes when the buttoon is clicked. The code is as follows:
MainActivity.java:-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Button myButton;
myButton = (Button)findViewById(R.id.enter);
myButton.setOnClickListener(new OnClickListener() {
#Override
private void onClick () {
submit();
}
}
);
public void submit() {
// Getting text from the EditText View
EditText editText = (EditText) findViewById(R.id.name);
String text = editText.getText().toString();
// Creating an email intent
Intent email = new Intent(Intent ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, newString[]{"youremail#gmail.com"});
email.putExtra(Intent.EXTRA_SUBJECT, text);
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
}
}
activity_main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:hint="Name"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/submit"
android:onClick="submit"
android:id="#+id/enter" />
</LinearLayout>
You don't need the line:
if (intent.resolveActivity(getPackageManager()) != null) {
Also, I believe that Intent.EXTRA_EMAIL takes a string array. Instead, try this:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"xyz#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, text);
startActivity(Intent.createChooser(intent, "Send Email"));
Yeah, what mattfred has answered is correct. Do as he told. And then also if that not work then remove
onClick:"Submit"
from your Button attribute.
Give your button a specfic id and initialize Button in your activity.
Button myButton;
Then activity's onCreate
myButton = (Button)findViewById(R.id.yourButtonId);
myButton.setOnClickListener(new OnClickListener(){
#Override
private void onClick(){
submit();
}
});
I think I have found a bug.
Replace your submit method as I have done
public void submit(){
// Getting text from the EditText View
EditText editText = (EditText)findViewById(R.id.name);
String text = editText.getText().toString();
// Creating an email intent
Intent email =new Intent(Intent ACTION_SEND);
email.setType("text/plain");
email.putExtra(Intent.EXTRA_EMAIL,new String[]{"youremail#gmail.com"});
email.putExtra(Intent.EXTRA_SUBJECT, text);
startActivity(Intent.createChooser(email,"Choose an Email client :"));
What you were doing wrong is you were getting text from a TextView. You have to get it from an EditText
Moreover, in your submit method you have initialized TextView with ID R.id.name. But there is no TextView in your xml and in your xml, your EditText is initialized with ID R.id.name.
More bug is found...
In your xml's Button attribute you have written
android:onClick="Submit"
But your method name is
submit() not Submit()
Remember, Java is case sensitive...
Also see, I think you can simply use
public void submit(){}
You have no reason to use
public void submit(View v){}
After all, change every code as I have told. Not only the method. You also remove
android:onClick="submit"
also from your XML's button attribute.
Hope you have understood
--Sorry for my mistyped code. Actually now I am on Mobile device