简体   繁体   中英

How to change text on button when the button has a particular current text (Android Studio/Java&XML)

So I'm trying to do a very simple thing, and for some reason I can't figure out how to do it. I've tried searching online but keep coming to resources that don't quite answer my question. How do you change the text on a button, not if that button is pressed, but if any button is pressed and the text on the pressed button equals some value? All my strings are saved in a strings.xml file and I'm just referencing them in my fragment_main.xml (using, for example, android:text="@string/firstoption" , but I can hardcode the strings if that's easier. I'm also using fragments, so should I put the onClick method in MainActivityFragment.java or MainActivity.java?

Try to create 2 div for your button. Show and hide the div on button click event. Use #divid to get the div. alternatively button text should be a dynamic value which should change on any button click on page ur on.

With the below code, you will make a generic OnClickListener "buttonClickListener". You can then add the same click listener to all of the buttons that you want to listen too. In this case, button1,2, and 3. When you click on either of those buttons, the buttonClickListener will be invoked. The View v paramater will be the reference of the view that triggered this event, in our case, whichever button was pressed. You can then cast v to type Button and check the text of the button that was clicked. If it is a certain value, you can set the text of the desired button, in this case, buttonToSetText button.

    final OnClickListener buttonClickListener = new OnClickListener() {
            public void onClick(final View v) {
                Button b = (Button)v;
                if(b.getText().toString().equals("something")){
                   buttonToSetText.setText("value to set");
                }               
            }
        };
        Button buttonToSetText = (Button) findViewById(R.id.buttonToSetText);

        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
        Button button3 = (Button) findViewById(R.id.button3);

        button1.setOnClickListener(buttonClickListener);
        button2.setOnClickListener(buttonClickListener);
        button3.setOnClickListener(buttonClickListener);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM