Simple android questions - android

So I've been looking around for android tutorials, help questions, etc.. I keep running into questions or tutorials hard for me to understand.
Here's my questions:
When I create an item in the visual designer, piece of code will be created in the .xml.
How can I get the ID of that item to use it in the .java file later?
How can I add callbacks when let's say a button gets clicked?
Here's what I have so far:
.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Button_click_callback() // Where to add the callback in the .xml?
{
// How to get button ID and change the text of it?
//Knowing this will help me A LOT!
}
}
.xml
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="79dp"
android:layout_marginTop="32dp"
android:text="Button" />

When I create an item in the visual designer, piece of code will be created in the .xml. How can I get the ID of that item to use it in the .java file later?
Step #1: Ensure that you have assigned an ID for the widget in the designer (in your XML above, you will see this as android:id="#+id/button1)
Step #2: In Java, you can get at the Java object for that widget by calling findViewById(R.id.button1) at some appropriate time (e.g., from an Activity, sometime after you call setContentView()).
How can I add callbacks when let's say a button gets clicked?
Generally, there is a setter method for this, such as setOnClickListener() that you can call on the Button you retrieved by findViewById().
In the specific case of click events on widgets hosted by activities, there is also an android:onClick attribute you can have in the XML, which supplies the name of a method on your Activity that will get called when the widget is clicked, instead of your having to use the setter.

#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something in response to button click
}
});
}
All of this is extensively documented on the Android Developer site. You should be looking their for this basic stuff.
http://developer.android.com/guide/topics/ui/controls/button.html

You can use findViewById to get view ids from XML in Java, Make sure that you should declare the ids in views, otherwise it might cause exception which results apps force close
If you want call back with xml rather than programatically
you can declare android:onClick attribute on that Views in layout XML
For example, in your case you need add android:onClick="Button_click_callback" in your
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="79dp"
android:layout_marginTop="32dp"
android:text="Button"
android:onClick="Button_click_callback"/>
then you can use Button_click_callback method for call back in your Activity
public void Button_click_callback()
{
}
if you want call back programatically with java,
first you have get the view with findViewById and then you can add click listener to that view

You need to use the onClickListener and override the onClick method.
btn.setOnClickListener.(new View.OnClickListener(){
#Override
public void onClick(View v) {
//TO DO
}
});
OnClickListener is an interface. And thats why you need to override the OnClick method.

//in oncreate method of activity
//take button id like that
Button button1 = (Button)findViewById(R.id.button1);
//then implement on click listener for performing action on button
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something in response to button click
}
});
}
//you can also implements onclicklistener in activity.its interface;
public class MainActivity extends Activity implements View.OnClickListener
//then generate method
public void onClick(View view) {
}

public class MainActivity extends Activity {
private Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Button_click_callback() {
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something in response to button click
Log.e("click", "-------------button click");
}
});
}
}

Those two code snippets are equal, just implemented in two different ways.
Code Implementation
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
});
// some more code
public void myFancyMethod(View v) {
// does something very interesting
}
Above is a code implementation of an OnClickListener. And this is the XML implementation.
XML Implementation
<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myFancyMethod" />

1) First Look at your XML file.In code it shows
android:id="#+id/button1.
You can edit it on your own name.Same thing you can do to change it though the GUI appear at right side of your design.
You can get your ID using findViewById(R.id.your id name); function.
For an Example:
My button id is btn1.In my code I can use that button by getting it's Id as follows:
Button btn1=findViewById(R.id.btn1);
2)You can callback after creating your Button which you have created Before as follows;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create your code
}
});
}

For the call backs - The android component needs to be registered in the calling device . The id of the components has to be unique in the xmls.
Using the unique id the components can be dynamically altered or the call backs can be used.

Related

Button click listener in xml

For button click listeners code runs fine when click listeners are defined in the activity but facing problem when defining click listener in the xml, no spelling mismatch
following error on logcat appears when listener are defined in xml, why?
java.lang.IllegalStateException: Could not find method addButtonClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'addButton'
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/addButton"
android:layout_marginTop="50dp"
android:onClick="addButtonClicked"
android:layout_below="#+id/inputField"
android:layout_alignLeft="#+id/inputField"
android:layout_alignStart="#+id/inputField" />
This is Activity Class
When click listener is defined in xml
public void addButtonClicked()
{
String text = inputField.getText().toString();
Products p = new Products(text);
dbObj.addProduct(p);
printDatabase();
}
When click listener is defined from Activity, This works fine
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String text = inputField.getText().toString();
Products p = new Products(text);
dbObj.addProduct(p);
printDatabase();
}
});
Add this to you activity:
public void addButtonClicked(View view) {
//Your code here
}
Could not find method addButtonClicked(View)
addButtonClicked() method Missing .
Create addButtonClicked() method first .
public void addButtonClicked(View v)
{
// Add your Staff here
}
Clean-Rebuild-Run .

Android How to set click listener of a button which is from another layout xml file

MainActivity shows a viewpager
so there are 3 layout files:activity_main.xml、card1.xml and card2.xml
Now I want to get view from card1.xml and set the listener.
what should I do?
I tried using this:
LayoutInflater layout=this.getLayoutInflater();
View view=layout.inflate(R.layout.card1, null);
Button b=(Button)view.findViewById(R.id.b);
then set OnClickListener:
b.setOnClickListener(new MyClickListener(0));
but useless.
In your card1.xml, you can add a onClick attribute, and just provide the method name as the attribute's value, like this:
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myMethod" />
Now in you MainActivity.java file, create a public method with return type as void, and which takes in a View parameter, like this:
public void myMethod(View v) {
// do your thing here
}
You can read more about it here.
public class MyClickListener implements OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.your_btn_id:
// your code
break;
}
}
}
another way is you can add button click listener in your card1.xml fragment class.

android wear gridviewpager onClick Listener

I'm developing a simple application in which youb have different spots placed on google map.
When I click on a spot I get its details which are displayed in a GridViewPager.
For now my application is based on the GridViewPager sample available with the sdk.
Here is my layout for the spot details (nothing fancy)
<android.support.wearable.view.GridViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"/>
My problem now is that I'm not able to detect a Click event on a card.
I've tried this but it doesn't work.
public class DetailsActivity extends Activity implements GridViewPager.OnClickListener {
#Override
public void onClick(View v) {
}
I've also tried View.OnClickListener.
Have any idea ?
There are two issues here. First, if you really want to make the GridViewPager clickable, you need to tell it to listen for click events - just implementing the OnClickListener interface isn't sufficient. So you need to do something like this:
public class DetailsActivity ... {
#Override
public void onCreate(Bundle savedInstanceState) {
...
GridViewPager pager = (GridViewPager)findViewById(R.id.pager);
pager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// put your onClick logic here
}
});
...
}
}
That being said, however, based on your description it sounds like what you actually want is to set up click handlers on individual pages within the grid, not on the entire grid. If so, then you'll need to do something similar but in each page's Fragment class. For example:
public class MyPageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(...);
result.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// put your onClick logic here
}
});
...
return result;
}
}
Note: if you are using CardFragments in your GridViewPager, then you would probably set the OnClickListener in your onCreateContentView override. Otherwise, the above Fragment-based example should apply.

How to implement click event in BaseActivity in android

I am implementing common header in all activity.I want to implement click event for header.can anybody tell how to implement click event in BaseActivity(Parent Activity) in android.I am getting reference in parent activity .Is it possible to implement click using setOnClickListener in parent activity?
txtHeading =(TextView)findViewById(R.id.txtHeading);
I want to implement click event for textview in parent activity
Any help would be highly appreciated
I usually create some helper method on the parent activity
public void setHeaderOnClick(View.onClickListener clickListener){
txtHeading =(TextView)findViewById(R.id.txtHeading);
txtHeading.setOnClickListener(clickListener);
}
when on the fragment, you can use
((YourActivityName)getActivity()).setHeaderOnClick(new View.OnClickListener() {
#Override
public void onClick(View v) {
//method here
}
});
hope it helps
yes you can do it like...
1.)in your header a xml in the textView set these properties.
android:clickable="true"
android:onClick="onClick"
2.) write the direct public void onClick() in your BaseActivity Like
public void onClick(View v){
if(v.getId() == R.id.txtHeading){
}
}
it will working charm yes after doing these steps don't find your text view component in BaseActivity.

What do I use as a parameter for the setOnClickListener() method?

I'm trying to make multiple OnClickListener methods for 5 buttons in my program, and I've been able to declare them, and I made a switch using the xml id of what was clicked, but I need a parameter for the setOnClickListener method when I call it, and all that will work is null. I have also tried passing in this, so the method has context.
Here's some of the code:
add.setOnClickListener(null);
sub.setOnClickListener(null);
mult.setOnClickListener(null);
div.setOnClickListener(null);
equal.setOnClickListener(null);
The parameter has to be an instance of some object that implements the OnClickListener interface. One way to do it is to use an anonymous inner class:
add.setOnClickListener(new OnClickListener{
public void onClick(View view){
//your event handler code here
}
});
another way is to make your class implement OnClickListener --do that by changing your declaration to look like:
public class MyActivity extends Activity implements OnClickListener{
then define an implementation for the onClick method:
public void onClick(View view){
if(view == add){
//handle add button click
}else if (view == sub){
//handle sub button click
}
//etc
}
then to install the listener you could do:
add.setOnClickListener(this);
You are supposed to pass View.OnClickListener to this function, which is a listener that will get called once the button is clicked.
To do that, you can either:
Declare this listener in the layout XML, with the button, as specified in Button 4 in this site.
Create an instance of View.OnClickListener and pass it to setOnClickListener method as in the example below (Taken from android site which is a great source):
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
...
}
Since View.OnClickListener is an interface, your activity may implement it as well, and be itself the listener, in this case, you will pass the activity instance(this) to the setOnClickListener method, but this is just one option, and not that recommended IMHO.
Coming from a .NET background, I struggled with the same thing at first. It's just a different syntax than .NET as java doesn't support properties, or events like I was used to. Here's a simple example of how to do this using a class level click listener variable...
#Override
private void onCreate(Bundle bundle) {
myButton.setOnClickListener(this.genericButtonListener);
}
private OnClickListener genericButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
//v represents your button
}
};
You need a concrete class here. For example:
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code here
}
});
If you look at documentation, you will notice it takes View.OnClickListener as parameter. If you need five separate listeners, which you are not going to use anywhere else, you can pass an anonymous class implementing onClick(View v), like this
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//do required actions here
}
});

Categories

Resources