Reputation: 428
i have dynamically added fragment(which is inflated from secfrag.xml) in main activity. there are two buttons in my main activity. one for adding fragment and the other is for changing text of my fragment. i have successfully added fragment to my activity but i can not change the textview text of my fragment. how can i do that.
public class MyActivity extends ActionBarActivity {
Button addFragment;
Button changeFragText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
addFragment = (Button) findViewById(R.id.mybtn);
changeFragText = (Button) findViewById(R.id.mybtn2);
addFragment.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Secfragjava secfragjava = new Secfragjava();
getFragmentManager().beginTransaction().add(R.id.mainholder, secfragjava).commit();
}
});
changeFragText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//how can i have the fragment and change its textview
TextView frv=(TextView) getFragmentManager().findFragmentById(R.id.container).getView().findViewById(R.id.mysecText);
frv.setText("raton");
}
});
}
Upvotes: 1
Views: 7068
Reputation: 6928
You should create a method inside of your fragment for changing the text.
e.g.
public void changeText(){
//this textview should be bound in the fragment onCreate as a member variable
TextView frv=(TextView) getView().findViewById(R.id.mysecText);
frv.setText("raton");
}
Then in your onClickListener you can just call that method:
((Secfragjava)getFragmentManager().findFragmentById(R.id.container)).changeText();
Upvotes: 4