我有一个mainactivity布局和另一个带textview的布局。我想从mainactivity文件中将值设置为textview并将其显示在mainlayout文件中。我怎么能这样做呢。我正在使用布局充气器并成功获得Textview的引用ID。
主要活动:
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>
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>
答案 0 :(得分:1)
您可以使用intent并将值传递给下一个Activity。您只需对布局进行充气,但不会将其添加到“活动”。
您必须获得RelativeLayout
的引用并将膨胀的视图添加到其中
拥有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");
答案 1 :(得分:0)
在 MainActivity.java
中执行此类操作View view;
/* We inflate the xml which gives us a view */
view = mInflater.inflate(R.layout.my_list_custom_row, false);
/* Get the widget with id name which is defined in the xml of the row */
TextView name = (TextView) view.findViewById(R.id.name);
/* Populate the row's xml with info from the item */
name.setText(myObject.getName());
其中mInflater是LayoutInflator的Object。 或者查看this链接。 希望这有帮助。