【发布时间】:2016-04-26 22:52:35
【问题描述】:
我使用java 在activity_main.xml 中插入一个片段,我将片段以线性布局放置在activity_main 中。 片段 xml 文件有一个 textView。
当应用程序使用 java 从 MainActivity 启动时、应用程序启动时以及调用 onCreate 时,我如何更改 TextView? 我尝试了一些解决方案形式 stacoverflow 但我可以让它工作。 当他开始加载应用程序时,模拟器会崩溃。
这里是activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
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="com.example.android.fragment_promjenaviewprekojave.MainActivity">
<LinearLayout
android:id="@+id/linearLayoutFragment_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
这里是片段代码:
package com.example.android.fragment_promjenaviewprekojave;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
这是只包含 1 个 TextView 的片段的 xml 文件
<LinearLayout 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"
tools:context="com.example.android.fragment_promjenaviewprekojave.BlankFragment">
<TextView
android:id="@+id/fragmentTextView_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
这是我要更改片段TextView的MainActivity.java
package com.example.android.fragment_promjenaviewprekojave;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BlankFragment objA = new BlankFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.linearLayoutFragment_id, objA);
fragmentTransaction.commit();
TextView textView = (TextView) findViewById(R.id.fragmentTextView_id);
textView.setText("We add text to fragment TextView");
}
}
【问题讨论】: