如何从 android studio 上的片段更改文本视图

How change a textview from a fragment on android studio

我有问题。我有一个 activity 实现了几个片段。现在我需要更新其中一个片段的文本视图,我在 activity 中有字符串,所以我需要将这个字符串传递给片段并更新那个文本视图。

NavigationDrawer.java --> 这是 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 --> 这是片段

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;

}

此类问题可以使用 Localbroadcast Receiver 解决。在您的片段中编写以下代码。像这样

@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);
    }
};

然后在您想要传递

时,通过在您的 activity 中添加以下代码来传递用户值
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", user);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

如果我对你的问题理解正确,你需要在你的片段交易中的 replacecommit 之前添加 inicialpage.setArguments(bundle);

然后,在你的 Fragment 中调用

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

检索它。

您已经创建了一个包,所以我假设这就是您要发送的数据。不过,您必须在片段交易之前将该捆绑包附加到片段。

在你的 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();

在你的片段中:

//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);