Android Textview 在 Fragment 中无法显示文本

3

我正在尝试将一个Fragment添加到我的FrameLayout中,看起来似乎已经成功添加,但是我无法看到TextView的文本。

Fragment布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/text1"
        android:text="Hello"
        android:background="#34f5d6"/>
</LinearLayout>

FragmentClass: 碎片类:
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class TimerClass extends Fragment {
        public static Fragment newInstance(Context context) {
            TimerClass fragment = new TimerClass();
            return fragment;
        }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
        ViewGroup root=(ViewGroup)inflater.inflate(R.layout.mylayout,container,false);

        return root;
    }
}

我使用的代码将片段添加到FrameLayout中:

    FragmentTransaction tx= getFragmentManager().beginTransaction();
    Fragment fragment= TimerClass.newInstance(getApplicationContext());
    tx.replace(R.id.fl, fragment);
    tx.commit();

我不明白为什么文本没有显示出来,我试图更改文本的颜色,但它不起作用。 如果我改变TextView的背景,它就起作用;如果我在TextView上添加一个OnClockListener监听器,它也可以工作。只是它不显示文本。
你能帮我吗?
编辑: 我找到了解决方案:问题出在FrameLayout上;它的顶部被操作栏遮盖。 通过调整FrameLayout的布局,问题消失了。
2个回答

0

首先,简单地更改这个

    ViewGroup root=(ViewGroup)inflater.inflate(R.layout.mylayout,container,false);
    return root;

    View root = inflater.inflate(R.layout.mylayout,container,false);
    return root;

还有这个

 public static Fragment newInstance(Context context) {
        TimerClass fragment = new TimerClass();
        return fragment;
    }

public static TimerClass getInstance() {
    TimerClass fragment = new TimerClass();
    return fragment;
}

0

我认为问题只出在你的TextView的高度和宽度上,因为你将它们设置为match_parent。

所以尝试替换一下

<TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/text1"
        android:text="Hello"
        android:background="#34f5d6"/>

使用

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text1"
        android:text="Hello"
        android:background="#34f5d6"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接