How to Visible/Invisible using OnClickListener? - java

I am working on FAQ page I don't want to use Expandable list view and stuff.
So I set 2 TextViews(1 for Question and 1 for Answer) and made one clickable.
The above image shows when the first textview mfaq is clicked it sets second one mAns to visible.
The below code works well to Set the mAns textview visible:
public class faq extends AppCompatActivity {
TextView mfaq,mAns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faq);
mfaq=findViewById(R.id.faq);
mAns=findViewById(R.id.ans);
mfaq.setOnClickListener(new View.OnClickListener() {
int counter=0; //setting counter to count onclick
#Override
public void onClick(View view) {
++counter; //incrementing counter first click
if(counter==1){
mAns.setVisibility(View.VISIBLE);
}
//this sets mAns visible , but when i click on it again i want it to hide the text view
counter=0; //resetting the counter
}
});
}
}
So I want to set the visibilty to gone when the textview is clicked again(Should function like Click-visible,ClickAgain-Invisible,Repeat).
Note-I am a beginner please try to explain me what the code is doing so I learn more :)
Thanks.

If I understand well you wanna hide/show your textview each time you click on the other text?
mfaq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mAns.getVisibility() == View.VISIBLE){
mAns.setVisibility(View.GONE);
}
else
mAns.setVisibility(View.VISIBLE);
}
});

Related

Call void method from another method in the same class

At first my main problem was at how to call a method from the same class, even tough I think I found a way to do this, it's not working as I expected, and I would like to know what would be the best approach to my case.
This is the code I'm working on:
public class EscolhaAtendimento extends AppCompatActivity {
private ViewPager mSlideViewPager;
private LinearLayout mDotLayout;
String TAG = "TasksSample";
private TextView[] mDots;
private SliderAdapter sliderAdapter;
Dialog myDialog;
#Override
public void onCreate (Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.escolha_atendimento);
mSlideViewPager = findViewById(R.id.slideViewPager);
mDotLayout = findViewById(R.id.dotsLayout);
sliderAdapter = new SliderAdapter(this);
mSlideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSlideViewPager.addOnPageChangeListener(viewListener);
myDialog = new Dialog(this);
}
public void addDotsIndicator(int position){
mDots = new TextView[8];
mDotLayout.removeAllViews();
for (int i= 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if (mDots.length > 0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected (int i) {
switch (i) {
case 0: {
myDialog.show();
}
addDotsIndicator(i);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
public void ShowPopup(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
}
This class is an activity that on user swipe, the text and image from the buttons will change, even though their IDs will stay the same. (That's controlled by another class, it's working well).
Now, I wanted the image button on the activity do something different depending on which page is selected, and that's why there is a initial switch on the onPageSelected method, inside the Page change listener. The image button in the layout has the android:onClick="ShowPopup" tag, and I guess that also complicates things for me, if I wanted it to do something different in that same activity? Also, calling it that way on the switch, every time I change pages, and go back to the first one the popup window will open, since my call is explicit there. (As I said, even tough I found a way to somehow call my method, or at least it's result, it's not working as I expected).
Edit
I tried then changing it like this, so that the button wouldn't rely on the android:onClick="ShowPopup" Tag, and also wouldn't need to call a void method directly on the switch:
Added
public ImageButton popupchoice;
And also this to onCreate method:
popupchoice = this.findViewById(R.id.imgslide1);
Inside the switch I called it like this to get the button ID:
popupchoice.setOnClickListener(image1);
And set the View.OnClickListener like this:
View.OnClickListener image1 = new View.OnClickListener() {
public void onClick(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
};
But that returns me:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at .EscolhaAtendimento$1.onPageSelected(EscolhaAtendimento.java:81) Line 81 is the one inside the switch with the popupchoice.setOnClickListener(image1).
This error happens on page change, when coming back to the first Page, and also the button click won't work anymore.
I think you can use
EscolhaAtendimento.this.ShowPopup from inside your switch.

onBindViewHolder increase position onClickListener

I have an activity with two buttons Next and Previous and a textview, I would like to update the textview content each time I click Next or Back
For example, If I click Next the textview should show me content from the next position or vice versa.
I think that I should be using a loop but it gives me an error when I try to do that and when I add 1 to the position (i+1) it works but it only gives me the second position, I want to get all the positions not only the second one. I don't really know if my question is clear, Hope it is :)
onBindViewHolder
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, #SuppressLint("RecyclerView") final int i) {
myViewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nextContent = listItems.get(i).getContent();
String previousContent = listItems.get(i).getContent();
Intent intent = new Intent(v.getContext(), Main2Activity.class);
intent.putExtra("next", nextContent);
intent.putExtra("prev", previousContent);
v.getContext().startActivity(intent);
}
});
}
Main2Activity
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemTextView.setText(nextContent);
}
});
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemTextView.setText(prevContent);
}
});
It's bad practice to set click listeners in the onBindViewHolder method.
Why? Because onBindViewHolder is called each time the views are recycled for the new content to be displayed on the screen. Say you have a list of 1000 elements with 10 of them visible on the screen.
You scroll it to the end => Then onBindViewHolder would be called 990 times => 990 click listeners set.
You also want to dodge costly operations in onBindViewHolder() because your scrolling would be potentially slowed down.
More tips here:
Recyclerview(Getting item on Recyclerview)
A loop isn't the answer here, a loop is for automating something. This is an event (the user interacted) so it's not suitable.
The algorithm you probably want is basically the following:
User clicked an item
Find out the item index
Increment the index
Find the item with that index (by asking the list)
If it exists, do something with it
However, the issue in the code you posted is that your 'nextContent' is always the current item. So you need the following change (but be careful about bounds):
String nextContent = listItems.get(i+1).getContent();
String previousContent = listItems.get(i-1).getContent();
You current code isn't using a loop, so the onBind method should be called once for each value of i so it should not always be the second item
After your comments it appears you have buttons unrelated to the list, so now what you need to do is make it so every time you click an item in the RV or a Next/Prev, you store the correct index (as you have no access to i)
In the activity:
private int currentTextItem = 0;
public void setCurrentTextItem(int i) {
currentTextItem = i;
//the dots here will be how you get the text from the item
// probably recyclerView.findViewHolderForAdapterPosition(pos)
myTextView.setText( ... );
}
In your view holder code:
myViewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//(You should have some kind of call back from viewholder to activity)
activity.setCurrentTextItem(i);
}
});
Then your next/prev:
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setCurrentTextItem(currentTextItem + 1);
}
});
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setCurrentTextItem(currentTextItem - 1);
}
});

Buttons outside the onCreate

Always in my apps I added buttons in void onCreate, but now I'm trying to do app with more buttons (about 10). I would like to all buttons active on start app.
In my opinion it is too much buttons to add in this onCreate and app will be starting to long.
I tried to put this:
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
})
out of onCreate
but AndroidStudio underlines setOnClickListener and view
I don't have ideas, how and where can i add button out of onCreate.
If you don't want to overcrowd your oncreate method, then create a clicklistener outside onCreate anywhere in activity and in onCreate just set it.
onCreate :
edit_a_member = (Button) findViewById(R.id.edit_member);
delete_a_member = (Button) findViewById(R.id.delete_member);
edit_a_member.setOnClickListener(handleClick);
delete_a_member.setOnClickListener(handleClick);
clickListener:
private View.OnClickListener handleClick = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.edit_member:
member_selected = EDIT_MEMBER_SELECTED;
callDialog();
break;
case R.id.delete_member:
callDeleteAlert();
break;
}
}
};
You can simply add a separate method for your buttons in the same class, e.g.:
public void onCreate(...){
//Standard setup of views or whatever you want to do here
this.addButtons();
}
private void addButtons(){
Button b1 = new Button("Hi");
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
Button b2 = new Button("Hi to you too");
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
}
This is an example. You can do this in soooo many ways. I feel like you should thoroughly learn Java's fundamental Object Oriented programming, because that's really what your question suggests you don't understand. Go follow a youtube tutorial. I always like "The New Boston"'s Java tutorial series on youtube.
PS: You can make code like this beautiful under the 'Words of wisdom': Don't repeat yourself
If you have to do a lot of work in your onCreate but you are worried that the UI will take too long to load you can always post a delayed runnable to a handler so in the onCreate method put :
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//add your code here
}
},10);
what this will do is your UI will load then the code in your Runnable will be executed 10 milliseconds after your UI loads thus your app will not take too long to load the UI, even though in your case I doubt it would be necessary.
If you are declaring the buttons in xml file :
Add these properties in each button Declaration in your Xml :
android:clickable="true"
android:onClick="onClick"
And now in Activity Class create a method like this :
public void onClick(View v){
switch(v.getId){
case R.id.{buttons_id_in_xml}
(Your Code)
break;
(Like for others)
}
}
If you want to add buttons dynamically :
Create a method to add the button like this:
void addButton(String buttonName, int button id){
Button button = new Button(this);
button.setText("Push Me");
(add it to parent Layout of xml)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(id){
case id1:
(handle )
break;
(like for others)
}
}
});
}
The best way to do this is:
add implements View.OnClickListener to
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// declare variables
private Button mBtn1;
private Button mBtn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// make an instance to the btns
mBtn1 = findViewById(R.id.btn1);
mBtn2 = findViewById(R.id.btn2);
// set onClickListener
mBtn1.setOnClickListener(this); // with "this" you are passing the view
mBtn2.setOnClickListener(this);
}
// implement onClick
#Override
public void onClick(View view) {
// check which btn was clicked by id
switch (view.getId()) {
case R.id.btn1:
btn1Clicked();
break;
case R.id.btn2:
btn2Clicked();
break;
}
}
private void btn1Clicked() {
// your code btn1 clicked
}
private void btn2Clicked() {
// your code btn2 clicked
}
Hope this helped. Cheers!

Multiple Step Actions on one Button Click

I am currently trying to solve a java based problem on Android Studio.
I have puzzled my head over this problem looking in many forums and webpages to not find any solution in the last two days. So I am seeking for help here now.
I have programmed a Button that when clicked causes a textview to swipe out of the screen with an animation. After that I would like the old text ("First Text") of the Textview to be replaced with another text ("New Text") appearing on the same place where the old text was. All of this should happen with only one click on the button step-after-step.
My problem with my code is that the old text is replaced by the new text first and then causes the animation.
Does anybody now a solution for this problem?
I would be really very grateful for any help!
This is my code below.
public class FirstActivity extends AppCompatActivity {
Animation slideleft;
Button btn1;
TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
btn1 = (Button) findViewById(R.id.btn1);
txt1 = (TextView) findViewById(R.id.txt1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
slideleft = AnimationUtils.loadAnimation(FirstActivity.this, R.anim.slide_left);
txt1.startAnimation(slideleft);
txt1.setText("New Text");
}
});
}
}
you can use onAnimationEnd method of animation listener and change the text inside it.
animation.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationEnd(Animation anim) {
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setText("New Text");
}
});
you can place which event execute after the animation place your code
anim.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
//your_code
}
});

how to use java onclick shuffle array

I am learning how to use strings and onlclick in java. I have written a programme below which shuffle three names and then outputs them into three buttons.
When I click on Paul, I want the message to be displayed in message box. Since Paul will be in a button each time. I am puzzled on how to attach my message to Paul.
Paul moves around due to the use of array. I understand this is a tough question, but I also know, there are some very clever ppl out there who love a challenge.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void generate(View view) {
String [] names = new String[3];
names[0] = "Bob";
names[1] = "Paul";
names[2] = "Mike";
Button btn_a = (Button) findViewById(R.id.a);
Button btn_b = (Button) findViewById(R.id.b);
Button btn_c = (Button) findViewById(R.id.c);
TextView message = (TextView)findViewById(R.id.message);
Arrays.asList(names);
Collections.shuffle(Arrays.asList(names));
btn_a.setText(names[0]);
btn_b.setText(names[1]);
btn_c.setText(names[2]);
}
public void a1(View view) {
}
public void b1(View view) {
}
public void c1(View view) {
}
}
This is a trick practical implementation in Java where a single listener is used for multiple buttons, rather than one listener for each button, so that each button's content determines what happens, not each button's listener. Helps for dynamic button grids (i.e. an 8x8 chessboard) to not define 64 listeners and code them all.
I don't have an Android IDE on hand, so this is pseudo-code, but you should be able to get the gist from this.
//Create a Universal Listener for all our buttons
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText().toString(); //get the button's name
if(text.equals("Paul")) {
//do anything for Paul ONLY in here
}
}
});
btn_a.setOnClickListener(listener); //give all the buttons the same listener, but only Paul's listener will do anything when you click on it
btn_b.setOnClickListener(listener);
btn_c.setOnClickListener(listener);
Using info from: http://developer.android.com/reference/android/widget/Button.html and https://stackoverflow.com/a/5620816/2958086

Categories

Resources