我有一个创建3个片段的MainActivity。进入第一个片段后,我希望从该片段中更改此片段布局中的Textview。当我尝试以这种方式访问​​TextView时,无法在IDE中弹出“ findViewbyId”方法。有人可以帮我吗?这是我要执行的名为“ FragmentOne”的片段的代码。该代码用于“ FragmentOne.jav”

package com.iotaconcepts.aurum;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.iotaconcepts.aurum.R;

import java.io.*;
import java.util.*;


public class OneFrangment extends Fragment
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        Fragment fc=getTargetFragment();
        TextView tv=(TextView)fc.findViewById(R.id.textview);//NOT WORKING
        try
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(getActivity().getAssets().open("symp.txt")));
            String parse1;
            while((parse1=br.readLine())!=null)
            {
                Toast.makeText(getActivity(), parse1, Toast.LENGTH_LONG).show();
                tv.setText(parse1 + "\n");
            }
        }
        catch(Exception e)
        {
            tv.append("wtf\n");
            Toast.makeText(getActivity(),"SORRY!", Toast.LENGTH_LONG).show();
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}



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"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">
android:w
<TextView
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Hello"
    />

最佳答案

您需要先向视图分配inflater.inflate方法,然后才能从其中找到视图。

View v = inflater.inflate(R.layout.fragment_one, container, false);
TextView tv=(TextView)v.findViewById(R.id.textview);
...
return v;

关于java - 如何从 fragment 本身中更改 fragment 的文本 View ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33966873/

10-09 18:16