如何从其他布局显示TextView [英] How to display a TextView from another layout
问题描述
我有一个mainactivity布局和另一个带有textview的布局.我想从我的mainactivity文件中为textview设置值,并将其显示在mainlayout文件中.我该怎么办.我正在使用布局充气机,并且成功获取了Textview的参考ID.
I have a mainactivity layout and another layout with a textview. I want to set value to textview from my mainactivity file and display it in the mainlayout file. How can I go about this. I'm using layout inflator and am getting the refrence id of Textview successfully.
主要活动:
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
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>
Layout2.xml:
Layout2.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.您只会为版面充气,而不会添加到活动"中.
You can use intent and pass the value to the next Activity. You only inflate the layout but that is not added to Activity.
您将必须获得对RelativeLayout
的引用,并将膨胀后的视图添加到其中
You will have to get the reference to RelativeLayout
and add the inflated view to it
具有RelativeLAyout的ID
Have a id for RelativeLAyout
<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");
这篇关于如何从其他布局显示TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!