android - 如何从另一个布局显示 TextView

标签 android android-layout textview layout-inflater

我有一个 mainactivity 布局和另一个带有 TextView 的布局。我想从我的 mainactivity 文件中将值设置为 textview 并将其显示在 mainlayout 文件中。我该怎么办呢。我正在使用 LayoutInflater 并成功获取 Textview 的引用 id。

主要 Activity :

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View vi = inflater.inflate(R.layout.layout2, null); //log.xml is your file.
    TextView tv = (TextView)vi.findViewById(R.id.text1);

    System.out.println("Textview= "+tv);
    tv.setText("hELLLLOO");
}
}

Main_Layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>

布局2.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="match_parent"
android:orientation="vertical"
 >
 <TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    android:layout_gravity="center" 
    android:textColor="#000000"/>
 </LinearLayout>

最佳答案

您可以使用 Intent 并将值传递给下一个 Activity 。您仅 inflated layout ,但不会将其添加到 Activity 中。

您必须获取对 RelativeLayout 的引用并向其中添加 inflatedView

有一个RelativeLAyout的id

<RelativeLayout android:id="@+id/relativelayout

然后

RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
View vi = inflater.inflate(R.layout.layout2, null); //log.xml is your file.
TextView tv = (TextView)vi.findViewById(R.id.text1);
tv.setText("hELLLLOO");
rl.addView(vi);

您还可以使用

http://www.curious-creature.org/2009/02/25/android-layout-trick-2-include-to-reuse/

或者

MainActivity

Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("key","hello");
startActivity(intent);

然后在SecondActivity

// Inflate Layout 2 and set text to textview.
String value = getIntent().getStringExtra("key");

关于android - 如何从另一个布局显示 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22244155/

相关文章:

java - 带有 rtl 布局方向的 api 17 和 18 的 Tablayout 问题

android - fragment 内容被切断

android - 更改颜色并在 xml 中将 TextView 的部分加粗

android - ScrollView 中的可缩放 TextView

java - 将 Html.fromHtml 与 android 8 十六进制数字颜色资源一起使用

java - Apache OpenNLP POSModel(URL) 构造函数

来自url的Android ImageView

Android:layout_weight 在以编程方式设置时不起作用

android - 如何使用 Android 相机获取全分辨率和未压缩的图像数据?

Android检测手机锁定事件