How to set Different String in a Textview in Fragment while clicking different Button?

拟墨画扇 提交于 2019-11-30 09:52:50

问题


I'm new to Android app programming.

I have two Fragments - fragmentA.xml and fragmentB.xml.

In fragmentA there are two Buttons - Button One (id: btnOne) and Button Two (id: btnTwo).

In fragmentB there is TextView (id- textView)

In fragmentB java class there are two String - string1 and string2

Both buttons refers to fragmentB.

I want two set the textView text to string1 when I press Button One and string2 when I press Button Two.

How can I do that?

I was using following code in fragmentB java class to display only string1

public View onCreateView(
    LayoutInflater inflater, 
    ViewGroup container, 
    Bundle savedInstanceState) 
{
    View rootView = inflater.inflate(R.layout.oop_page,container,false);
    TextView textV = (TextView)rootView.findViewById(R.id.textView);
    textV.setText(string1);
    return rootView;
}

Can I use any if-else statement here?

Thanx


回答1:


Create a Global class in your project and define a public string ..

public class Global{
  public static String TEXT = "";
}

In your Fragment A change this TEXT on button click event..

but1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        Global.TEXT = "string 1";
    }
});
but2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        Global.TEXT = "string 2";
    }
});

same as on other button if you have

In your FragmentB just setText()....it will take lase value change to Text

text.setText(Global.TEXT);



回答2:


FragmentA.java

public boolean btn1Clicked, btn2Clicked = false;
        Button button1 = (Button) rootViewfindViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                btn1Clicked = true;
              }
            });

            Button button2 = (Button) rootView.findViewById(R.id.button2);
            button2.setOnClickListener(new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                btn2clicked = true;
              }
            });

FragmentB.java

 public View onCreateView(
        LayoutInflater inflater, 
        ViewGroup container, 
        Bundle savedInstanceState) 
    {
        View rootView = inflater.inflate(R.layout.oop_page,container,false);
        TextView tv1 = (TextView)rootView.findViewById(R.id.textView);
        if(!(FragmentA.btn1Clicked))
         {
        // Not Clicked
         }
        else{
           tv1.setText("Button 1 Clicked!")'
    }
        return rootView;
    }


来源:https://stackoverflow.com/questions/35182457/how-to-set-different-string-in-a-textview-in-fragment-while-clicking-different-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!