从活动中更新片段中的textView

时间:2018-08-01 20:36:25

标签: android

我在Fragment中有3个TextView。

在MainActivity中,我有一种方法,每10秒生成3个字符串。

现在我想从活动中更新TextView,但是我不知道如何。

有人可以给我建议吗?

2 个答案:

答案 0 :(得分:1)

为xml文件中的textview设置ID:android:id="@+id/myId  然后执行以下操作:

TextView textView = (TextView) findViewById(R.id.myId);
textView.setText("updated text");

答案 1 :(得分:1)

这可以通过在您的活动中使用接口并在生成字符串时将参数传递给片段的方式来实现:

public class MainActivity extends AppCompatActivity {
private OnGenerateStringListener onGenerateStringListener;


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

    onGenerateStringListener = (OnGenerateStringListener) this;

    onStartGenerateStringFragment();

    try {
        generateString();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void generateString() throws InterruptedException {

    // After string a is generated
    String a = "test one";
    onGenerateStringListener.onGeneratedString(a);

    // Sleep 10 secs
    Thread.sleep(10000);

    String b = "test Two";
    onGenerateStringListener.onGeneratedString(b);

    // Sleep 10 secs
    Thread.sleep(10000);

    String c = "test Three";
    onGenerateStringListener.onGeneratedString(c);

}

private void onStartGenerateStringFragment() {
 //Method to launch your fragment
}    

interface OnGenerateStringListener {
    void onGeneratedString(String string);
}

}

这是您的Fragment类:

public class FragmentTextView extends Fragment implements MainActivity.OnGenerateStringListener{

    private View view;
    private TextView textViewOne;
    private TextView textViewTwo;
    private TextView textViewThree;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view != null) {
            ViewGroup group = (ViewGroup) view.getParent();
            if (group != null) {
                group.removeView(view);
            }
        } else {
            view = inflater.inflate(R.layout.fragment_layout, container, false);
            textViewOne = view.findViewById(R.id.textViewOne);
            textViewTwo = view.findViewById(R.id.textViewTwo);
            textViewThree = view.findViewById(R.id.textViewThree);
        }
        return view;
    }


    @Override
    public void onGeneratedString(String string) {
        switch (string) {
            // Use a switch case to determine which text view gets what parameters
            // for the sake of the example, I just passed a dummy text view input
            case "test one":
                textViewOne.setText(string);
                break;
            case "test Two":
                textViewTwo.setText(string);
                break;
            case "test Three":
                textViewThree.setText(string);
                break;
        }
    }
}