从活动更改片段文本视图

问题描述 投票:0回答:2

我想从活动(不是片段类)更改片段文本视图。我该怎么做?我正在使用这个代码:

public void startChat() {
    FrameLayout layout = (FrameLayout)findViewById(R.id.container);
    layout.setVisibility(View.VISIBLE); 
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.container, new ConversationFragment());
    fragmentTransaction.commit();
    viewPager.setVisibility(View.GONE);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayHomeAsUpEnabled(true);
    TextView nameView=(TextView)findViewById(R.id.user_name);
    nameView.setText("asd");
}

此代码加载conversation_fragment.xml并想要更改textview,但我的应用程序崩溃了。

这里是conversation_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#878787" >

        <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="dfgdfgdf"
        android:textSize="20dp"
        android:layout_centerInParent="true"
        android:id="@+id/user_name"/>

    <EditText
    android:id="@+id/message"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
   />

    <Button 
        android:text="Gönder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="getFromUser"
        android:layout_marginTop="40dp"
        />

</RelativeLayout>
android android-fragments
2个回答
3
投票

您可以使用

findFragmentById
查找片段并调用更改文本的公共方法

(ConversationFragment) getFragmentManager().findFragmentById(R.id.yourid);

或者在创建类时保留该类的实例,然后再将其添加到片段管理器

conv = new ConversationFragment()
fragmentTransaction.add(R.id.container, conv);

然后只需使用

conv
或任何你所称的名称来调用公共方法

编辑:

您使用捆绑包将数据发送到片段

Bundle b = new Bundle()
b.putString("text",data)
conv.setArguments(b);

然后在您的片段中使用

getArguments()
获取参数,并从包中提取数据并根据需要使用它


1
投票

你可以这样制作

public class ConversationFragment extends Fragment {
    
    private TextView nameView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.conversation_fragment, null);
        nameView = (TextView) view.findViewById(R.id.user_name);
    }
    
    public void setText(String yourText){
        nameView.setText(yourText); 
    }
}

并在您的活动中调用方法 setText()

ConversationFragment conv = new ConversationFragment();
conv.setText("asd");
© www.soinside.com 2019 - 2024. All rights reserved.