setText未在另一个布局中显示文本

时间:2016-04-19 08:24:58

标签: android android-layout

我有一个程序,使用setContentView显示一个布局,同时我想更新另一个布局中的文本。

我发现文本没有更新,但是检索getText设置的值会给出更新的值。

我希望使用setText设置的值显示。

public static class Login_fragment extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

    }
    public void login_onClick(View view)
    {
        Toast.makeText(this,"Login Succesful",Toast.LENGTH_SHORT).show();

        startActivity(new Intent(this,MainActivity.class));  
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rootview=inflater.inflate(R.layout.nav_header_main,null,false);
        LinearLayout linearLayout=(LinearLayout)rootview.findViewById(R.id.nav_linear_id);
        TextView textView=(TextView) rootview.findViewById(R.id.login_name_drawer);
        String viewq=textView.getText().toString();
        Log.v("First",viewq);
        textView.setText("def");
        if(textView.getParent()!=null) {
            ((ViewGroup) textView.getParent()).removeView(textView);
        }
        linearLayout.addView(textView);
        viewq=textView.getText().toString();

        Log.v("Second",viewq);
    }

我的Xml布局文件是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:id="@+id/nav_linear_id">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/login_name_drawer"
android:text="abc"/>

</LinearLayout>

我希望文本更新并显示“def”

1 个答案:

答案 0 :(得分:0)

1。)使用SharedPreference将用户值存储在LoginActivity中。然后在MainActivity中从SharedPreference中检索值并将值设置为textView。

LoginActivity

echo "Even: {$even}<br/>"; //2
echo "Uneven {$uneven}";   //4

在MainActivity中oncreate()

      SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
MODE_PRIVATE);
     SharedPreferences.Editor editor = sharedPref.edit();
     editor.putString("user", "test");
     editor.commit();

2.使用Intent传递用户值设置MainActivity中的textView值。

LoginActivity

     SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
MODE_PRIVATE);
      String user=sharedPref.getString("user","");
     TextView textView=(TextView) findViewById(R.id.login_name_drawer);
     textView.setText(user);

在MainActivity onCreate()

     Intent intent = new Intent(this, MainActivity.class);
     intent.putExtra("user","value");
     startActivity(intent);

希望这有助于你