If I want to design a button that all java can use it without need to write it in every java,
what should I do?
For Example:
I design a Button.OnClickListener function to search bluetooth devices.
but another java also need to use this Button.OnClickListener function,
I don't want to write same way on two java.
ledWrite.xml:
<Button android:id="#+id/btnScan" />
<ToggleButton android:id="#+id/tBtnWrite" />
bluetoothUtils.java
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private Button button_scan;
button_scan = (Button)findViewById(R.id.button_scan);
button_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
scanbt();
}
});
private void scanbt(){
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
then I design LedWrite.java:
private ToggleButton digitalOutBtn; //LED On/OFF
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ledwrite);
digitalOutBtn = (ToggleButton)findViewById(R.id.tBtnWrite);
digitalOutBtn.setOnClickListener(new OnClickListener()
public void onClick(View v){
if(digitalOutBtn.isChecked()){ //sendMessage("D1"); }
else{sendMessage("D0";}
}
How can I use button_scan in LedWrite.java?
If you want to call a method defined is some other Activity on press of a button, then you can make that method as static.
Let's assume that you have a method named searchBluetooth() in MainActvity and you want to call it from SecondActivity.
Define searchBluetooth() in MainActvity like,
public static void searchBluetooth()
Call this method from SecondActivity like,
MainActivity.searchBluetooth()
If you don't want to use static because of memory consumption then try with inheritance.
Create a class CommonActivity which extends Activity class
class CommonActivity extends Activity
{
// here define your searchBluetooth method
public void searchBluetooth()
{
// your code here
}
}
If you want to make use of it in Second Activity then
class SecondActivity extends CommonActivity
{
// here you can access `searchBluetooth()` method
}
enclosure a BluetoothListener class?
public BluetoothListener implements OnClickListener {
#Override
public void onClick(View v) {
do something you want...
}
}
then invoke the class in two different class, eg,
button.setOnClickListener(new BluetoothListener());
I recently started learning android and this answer may have some error, if so, please let me know, Thanks.
Related
I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
tv.setText(months[rand.nextInt(12)]);
tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
}
});
It works like this. View.OnClickListenere is defined -
public interface OnClickListener {
void onClick(View v);
}
As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:
public class MyListener implements View.OnClickListener {
#Override
public void onClick (View v) {
// your code here;
}
}
But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.
setOnClickListener takes View.OnClickListener as its parameter.
This is the best way to implement Onclicklistener for many buttons in a row
implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
That what manual says about setOnClickListener method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view
is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
I have a public void in one class and I want to call it in another class when it creates but nothing seems to be working. here is the code of my first activity
public class activityone extends Activity {
public void actionC() {
//actions
}
Does anyone know how to call it in my second class?
In general, you need to have an instance of your activityone class in order to call an instance method.
To create an instance, you generally use a constructor like:
activityone a = new activityone();
a.actionC();
I'm not sure this is what you want though, because Activitys are generally created by the Android system itself and you should handle the onCreate method instead.
Here is what you can do:
public class activityone extends Activity {
/*public void actionC() {*/ //Instead on normal method, write your actions in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//actions
}
and in your second activity, do this:
Intent intent = new Intent(getApplicationContext(),activityone.class);
startActivity(intent);
Hope it helps !!!
I have a title bar in my application. And the title bar has one button. On click of that button I display info activity. Now, as far as I know, android:onClick needs a reference of a public method inside the activity which has the xml set in setContentView(). Now, as the logic for that buttons click will be the same throughout the application, so what I want is, I will the method just once say showInfoScreen(View view) and put it in that buttons onClick attribute. And I need not write the same method everywhere. Is it possible?
Of course it's possible. Write an Activity class, then have all of your Activitys extend it. For example:
public abstract class BaseActivity extends Activity {
#Override
public void setContentView( int layoutResID ) {
super.setContentView( layoutResID );
findViewById(R.id.button).setOnClickListener(new OnTitleBarButtonClickListener());
}
private void showInfoScreen() {
// Show the info screen
}
private class OnTitleBarButtonClickListener implements OnClickListener {
#Override
public void onClick(View v) {
showInfoScreen();
}
}
}
Then all of your derived Activitys would extend BaseActivity instead of Activity.
The beauty of doing it this way is that any Activity that extends this class automatically gets this feature. No coding is required in the derived classes, just in BaseActivity. The only contract all of your Activitys will have will be to have R.id.button or whatever id you name it within its content.
I think you have to write onclick in every Activity where you want to display infoscreen.
But OnClick you just call A method showInfoScreen(View view) in every Activity....
And you should create class Like...ShowInfo and there are one static method...
public class ShowInfo{
public static void showInfoScreen(View view,Context c){
//now dispay info here
}
}
Write ShowInfo.showInfoScreen(v,YourClassName.this) in your onClick() Method....
An example of what Vinayak.B suggested is like this:
public class yourAppUtils {
public static void yourMethod() {
// Do stuff
}
}
I've seen this asked a thousand times in a thousand different ways, but still can't get it to work...
I created a class which I've derived from ImageButton. I want to define my "on-click" behavior in the class.
I know I can do something inside my Activity's onCreate like:
myButton b;
b = (myButton)findViewById(R.drawable.mybutton);
b.setOnClickListener(new View.OnClickListener() {
...etc...
but I want to define the code where it should be, in the derived class.
I first thought I could define it as:
#Override public void onClick(View v) {
...but I get an error saying that I can't use "#Override" here because "onClick" isn't in the superclass. (When trying to remove "#Override", it just builds and runs, but never gets called). I've also tried:
#Override public void onClickListener(View v) {
...and several variants of "implements onClickListener" and "implements OnClickListener" to no avail.
This should be fairly simple - any ideas??
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
derivedClassFunction(v);
}
});
public void derivedClassFunction(View v) {
/* code...*/
}
Another way:
public class DerivedClass extends ImageButton implements View.OnClickListener {
/*code...*/
b.setOnClickListener(this);
/*code...*/
#Override
public void onClick(View v) {
/*code...*/
}
}
This is because there actually is no method onClick() in views. The work is done in the onUpKey() in the View class.
However, if you want to listen to clicking events in the subclass, this could be done very easily. You can either create an inner class which implements View.OnClickLister and use it to listen to events or even simpler, implement the interface in your class and set it as a listener during construction. The latter will look like this:
class YourClass extends ImageButton implements View.OnClickListener {
public YourClass() {
setOnClickListener(this);
}
#Override
public void onClick(View v) {
//Your code
}
}
LAS_VEGAS has already posted how the first variant with the inner class may look like.
I want to use a button click to pass selection parameters to another class that will build a map screen using the passed parameters. I am focused on getting my button action working. I a using onCLickListener and onCLickView as follows
Class1:
public class Class1 extends Activity implements OnClickListener {
Class2 class2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
..........
Button button = (Button)findViewById(R.id.btn_configup1);
button.setOnClickListener(this);
}
public void onClick(View v) {
Class2 class2 = new Class2();
//Save state.. selections and params and use bundle
//to pass into class2
class2.execMapBuild();
}
}
Class2:
public class Class2 extends MapActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.drawable.navup);
}
public void execMapBuild() {
finish(); //just in case we return.
Intent intent = new Intent(CLass2.this, Class2.class);
startActivity(intent);
}
I have everything working except the desired button action. I want the button click in Class1.onVlickView to call Class2.execMapBuild using the button click action. I have the button click capturing the action and calling the execMapBuild method on Class2. But I get a NullPointerException as it moves from startActivity(intent) into onCreate.
I have tried several other ways of nailing this down, but this seems the best and I seem close to figuring it out. I would really appreciate an explanation of what I may be missing.
Added code that was initially not copied in.
To expand on #Heiko Rupp's answer, if you want Class2 to display a map, it needs to extend something like Activity. As such, you can't just call it with a normal method. You need to register the Activity in your manifest and then call it using an Intent. Here is a sample of the kind of thing you should be doing:
public class Class1 extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Button button = (Button)findViewById(R.id.btn_configup1);
button.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = new Intent(Class1.this,Class2.class);
intent.putExtra("key","data");
...
startActivity(intent);
}
}
public class Class2 extends MapActivity {
String mData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
mData = extras.getString("key");
...
}
...
}
}
Can I also suggest that you use more descriptive class names than Class1 and Class2.
Class2 is no activity, so the callbacks of an Activity will not be called by the system.
And if it were an Activity, you could not just call into it via new Class2(), as still the callbacks are not executed.
Try to clean this up and then start Class2 activity from Class1 with an Intent as you are doing within execMapBuild().