Java Callback-like/event method? - java

I might be on the wrong track here, and should be thinking events/publish-subscriber, if so, please enlighten me.
I have an android project running, where I have a layout which acts as an on-screen menu. Implemented in several activities/"parent-views" with the use of '< include>'. Working nicely.
Now, some of the functionality is general and global. Like I have an "add"-button, which does something, that it should always do. Then I'd like the possibility to customize what it does in addition to this, based on the activity where the action originated.
I have seperated menulogic in a simple java class, with the constructor taking an activity as a parameter. From here, I can attach clicklisteners to the buttons in the menu fine, and do stuff on click.
What I'd like is something like:
private void addBtn(String text, String path) {
LinearLayout ll = (LinearLayout) parentActivity.findViewById(R.id.dynamicButtonLayout);
Button newButton = new Button(parentActivity);
newButton.setText(text);
newButton.setTag(path);
newButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do Stuff.
fireDoneHandlingButtonClick();
} catch (Exception e) {
}
}
});
}
And then have a way of handling this method in the parent activity. Should I be thinking of events, or should I be thinking of a way to add a method as an argument to the addBtn method from the activity, which can be fired from inside the click-listener?

Look at How To Implement Your Own Listener in Android or Fire and Forget Messages (events) in Android

Related

can I have two different onclick methods for one button

I wanted to know if its possible to have two onclick methods for one buttton..Im trying to have a button that can open a new activity and send a id token to the server for firebase purposes, if possible how do i go about it on android studio
I think you are getting the underlying concept wrong.
Buttons react to clicks.
The "ActionListener" that gets triggered on that click ... can do whatever it wants. There is nothing (conceptually) that prevents you in your code to just trigger various things. Of course, you have to understand what you are doing (things like: not blocking the UI thread for too long; or how to kick of things in background threads, and so on).
No. There is only one onClick method for a Button. But you can still perform two different purposes by one button.
I am using a button to hide and show a linear layout. The code is given below :
final int[] count = {2};
//here startTopics is the button....
startTopics.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(count[0] %2==0)
{
topicLin.setVisibility(View.VISIBLE);
count[0]++;
}
else
{
topicLin.setVisibility(View.GONE);
//here topicLin is the linear layout
count[0]++;
}
}
});
It is one button and so you should apply only one onClick listener which performs the buttons job.
In your onClick-method you can just call another (private) method if you want to do multiple things without sacrificing code management.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendTokenToServer();
// Include your code to open the activity here or outsource it again into another private method
}
});
And your method to send the token to the server:
private void sendTokenToServer() {
// Your code here.
}

Calling a method from an unknow(yet) class type

To put you in context, when the user clicks the floating action button the activity will check which fragment is active.
Then, depending on the fragment tag it will call a method in that specific instance.
I found a way to do it on this awesome forum but the only problem is that I don't understand what I'm doing here
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment.getTag() == "EXERCISES_LIST_FRAGMENT") {
//THIS IS THE PART I DONT UNDERSTAND
ArrayList t = ((ExercisesListFragment) fragment).GetArray();
//THIS IS THE PART I DONT UNDERSTAND
System.out.println(t.size());
}
}
});
It seems like casting a variable but I searched and did not see anything like this.
I want to know what is that part : ((SomeKindofClass) variable).SomeKindOfClassMethod();
I would like to read about that but I don't know how you name that
sorry for my English
Thanks

RecyclerView programmatically click

I'm trying to programmatically click on an item of a recyclerView. I'm using:
recyclerView.findViewHolderForAdapterPosition(index).itemView.performClick();
This perfectly works when the index is of a visible item. If the item is not visible (at the last position of the recyclerview, for istance), an Exception is thrown.
What can I do?
I just had a similar question with yours.And I had solve it! Here is what I did.
xxx.mRecyclerView.postDelayed(new Runnable() {
#Override
public void run() {
xx.mRecyclerView.scrollToPosition(position);
}
},300);
xxx.mRecyclerView.postDelayed(new Runnable() {
#Override
public void run() {
xxx.mRecyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();
}
},400);
}
You can scroll to the specific item, then perform click.
Because the doc say
If the item at the given position is not laid out, it will not create a new one.
But I know the adapter has the data, so scroll to it first, and findViewHolderForAdapterPositionwill not be null.
One more thing, I do not know how you use the RecyclerView. In my application, I use it in a fragment, and I don not know why we should delay it scroll and perform click. (Maybe it is because of the life circle?).But this really works.
You could call onClick directly, assuming that view manages its own click listener.
View view = recyclerView.findViewHolderForAdapterPosition(index).itemView;
view.onClick(view);
If the click listener is located somewhere else, you just need to get a reference to the object with the onClick method and call it with the correct view as a parameter.
try this for kotlin and viewBinding
viewBinding.catList.post {
val view = viewBinding.catList.findViewHolderForAdapterPosition(0)?.itemView?.findViewById<CheckBox>(R.id.catButton)
view?.callOnClick()
}

How to change color of background Android Java in Eclipse ADT

I am very new to mobile development, this isn't homework I am working ahead of my class, I developed a simple app that has a button and when it's pressed it shows a message "Hello Android". I would like to build on this and change the color of the background when the onClickListener is called, I will post my code below, I am asking for the best approach to achieve my goal (change background). I want to iterate that this code below works, and that I am not asking for anything to do with the code I have presented, I want to add to it to change the background color (it's currently white, I'm assuming by default). Oh and I have never worked with Java before (very difficult course teaching android/iOS/WinMobile in 1 class). Thank you.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupMessageButton();
}
private void setupMessageButton() {
// 1. Get a reference to the button
final Button messageButton = (Button) findViewById(R.id.helloDroidButton);
//Set the click listener to run my code.
//Code will run when user clicks button.
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Anonymous class? --> not sure what he means
Log.i("DemoButtonApp", "Hello Android!");
Toast.makeText(
MainActivity.this,
"Hello Android!",
Toast.LENGTH_LONG
).show();
}
});
}
Android support feature called Selector , that help you to change the background of any view in each state of it like pressed , forces and so one , take look on this useful tutorial and feed me back in any not obvious point
http://www.mkyong.com/android/android-imagebutton-selector-example/
hope it help you

Android OnClickListener complexity

I need to know, what is better in terms of complexity. Either to identity a separate onClick method from xml for each button like this:
android:onClick:"clickHandler"
and the java code:
public void clickHandler(View v){
Button b = (Button) v;
//do something for that button
};
, or identify one method for all of the buttons, and separate them with if conditions.
Public void clickHandler(View v){
Button b = (Button) v;
if(b.getText().equals("a")){
}
elseif(b.getText().equals("b")){
}
//And so on.
}
I am not that good in calculating complexity and so on, but this question just irritates and I can't answer it. But what I understand, the first method increases the code lines a lot!
I generally like the latter. Except I tend to do something that looks more like this:
public void onClick(View v){
switch(v.getId()){
case R.id.button_a:
//do button a logic here
break;
case R.id.button_b:
//do button b logic here
break;
}
}
Consider making your Activity implement View.OnClickListener than in your OnCreate() simple attach with findViewById(R.id.button_a).setOnClickListener(this);
I would use a version of the second option. Create one handler, and then use a switch statement to determine which view received the event. It is code efficient and is not messy at all. Also, you don't need to list that attribute in xml... I personally think it is much easier to findViewById() in your activity and implement onClickListener. Then you can use each button's id in your switch statement.

Categories

Resources