简体   繁体   中英

How change a textview from a fragment on android studio

I am having a problem. I have an activity that implements several fragments. Now I need to update a textview of one of the fragments, I have the string in the activity, so I need to pass this string to the fragment and update that textview.

NavigationDrawer.java --> this is the activity

String user = "";
InicialPage inicialpage = new InicialPage();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_naviagation_drawer);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
        user = extras.getString("KEY"); // TODO this is the value that i need to pass to the fragment InicialPage
    }

    Bundle bundle = new Bundle();
    bundle.putString("USER", user);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    android.support.v4.app.FragmentTransaction fragmenttransaction =
            getSupportFragmentManager().beginTransaction();

    fragmenttransaction.replace(R.id.container, inicialpage);
    fragmenttransaction.commit();

    //inicialpage.setUsernameTextView(user);

    DrawerLayout drawer1 = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer1.closeDrawer(GravityCompat.START);

    TextView userNameTextView = (TextView)findViewById(R.id.usernametext);
    //userNameTextView.setText(user);

    android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.InicialPage);

}
    @Override
    public void onBackPressed () {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu){
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.naviagation_drawer, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected (MenuItem item){
        // Handle navigation view item clicks here.

        int id = item.getItemId();
        android.support.v4.app.FragmentTransaction fragmenttransaction =
                getSupportFragmentManager().beginTransaction();

        if (id == R.id.InicialPage) {

            fragmenttransaction.replace(R.id.container, inicialpage);
            fragmenttransaction.commit();

        } else if (id == R.id.HistoryItem) {

            fragmenttransaction.replace(R.id.container, new Historic());
            fragmenttransaction.commit();

        } else if (id == R.id.FriendsItem) {

            fragmenttransaction.replace(R.id.container, new Friends());
            fragmenttransaction.commit();

        } else if (id == R.id.PointsItem) {

            fragmenttransaction.replace(R.id.container, new Points());
            fragmenttransaction.commit();

        } else if (id == R.id.BookBikeItem) {

            fragmenttransaction.replace(R.id.container, new BookBike());
            fragmenttransaction.commit();

        } else if (id == R.id.MessagesItem) {

            fragmenttransaction.replace(R.id.container, new Messages());
            fragmenttransaction.commit();

        }else if(id == R.id.Mapdebug)
        {
            Intent maps = new Intent(this,MapsActivity.class);
            startActivity(maps);

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

public void FrameClicked(View view) {
    //send user name to chat
    Intent i = new Intent(this, Chat.class);
    i.putExtra("USER", user);

    startActivity(i);
}

public void addFriend(View view) {
    LinearLayout principalLayout= (LinearLayout) findViewById(R.id.idFriendsVertical);
    LinearLayout secondaryLauout= new LinearLayout(this);
    TextView tx= new TextView(this);
    EditText et= (EditText) findViewById(R.id.ADD);

    String edittx= String.valueOf(et.getText().toString());
    if (edittx.equals("")) {
    }else
    {
        tx.setText(edittx);
        tx.setTextSize(22);
        tx.setTextColor(Color.BLACK);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
        params.setMargins(0, 20, 0, 10);

        secondaryLauout.addView(tx, params);
        principalLayout.addView(secondaryLauout);
    }
    et.setText("");
}

}

InicialPage.java --> this is the fragment

public class InicialPage extends Fragment {

SQLiteDatabase db;
View view;
TextView usernameTextView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.fragment_inicial_page, container, false);
    usernameTextView = (TextView) view.findViewById(R.id.usernametext);

    return view;

}

If I understand your question correctly, you need to add inicialpage.setArguments(bundle); before your replace and commit in your fragment transaction.

Then, inside your Fragment you call

Bundle bundle = getArguments();
String bundleText = bundle.getString("USER");

to retrieve it.

This type of problem can be solved using Localbroadcast Receiver .Write the following code in your fragment. Something like this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
....
LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter("custom-event-name"));
return view;

}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        // Get extra data included in the Intent
        String message = intent.getStringExtra("message");
usernameTextView.setText(message);
        Log.d("receiver", "Got message: " + message);
    }
};

then pass the user value by adding this following code in your activity when you want to pass

Intent intent = new Intent("custom-event-name");
intent.putExtra("message", user);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

You were already creating a bundle so I'm assuming that's the data you want to send. You have to attach that bundle to the Fragment before your Fragment Transaction though.

Inside your Activity:

Bundle bundle = new Bundle(); //create the bundle
bundle.putString("USER", user); //attach data to the bundle

inicialpage.setArguments(bundle); //set the bundle on the fragment

//perform fragment transaction
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();

Inside your Fragment:

//retrieve the bundle
Bundle bundle = getArguments(); //retrieve the bundle
String bundleText = bundle.getString("USER"); //get the data on the bundle

//find view & set the text
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
usernameTextView.setText(bundleText);

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