android - 如何以编程方式在表格行内添加 fragment ?

标签 android android-fragments

我可以用这个 xml 实现这个:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/startoverviewfragmentLayoutId" >

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.xxxx.xxx.MyMediaPlayer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TableRow>

</TableLayout>

但是我如何使用 Java 代码来实现呢?我试过这个:

    MyMediaPlayer mpv = new MyMediaPlayer(); //Fragment
    TableRow tt = (TableRow)myView.findViewById(R.id.tableRow1); 
    tt.addView(mpv);

但是由于 fragment 不是 View ,所以这行不通。那我该怎么办呢?

最佳答案

为了向后兼容地替换你的

<fragment
    android:id="@+id/fragment1"
    android:name="com.xxxx.xxx.MyMediaPlayer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<FrameLayout
    android:id="@+id/fragment1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>

在您的 Activity 中使用此代码

MyMediaPlayer myf = new MyMediaPlayer();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment1, myf);
transaction.commit();

关于android - 如何以编程方式在表格行内添加 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25218764/

相关文章:

android - 如何找到应用程序的主要 Activity 的名称?

android - 自定义 arrayadapter 组合了在同一 Activity 的不同 fragment 中使用的列表

java - YouTubeFragmentPlayer Android 应用程序 - 仅出现黑框

android - 遍历Fragment返回栈时如何刷新ActionBar导航项?

android - 本地化来自服务器的数据的android应用程序

android - 如何去除 appbar 的弹跳效果?

android - Android Studio 中抽屉导航菜单中第一项的上边距

android - 图像 GridView 内部 fragment

java - 具有动态 fragment 的 Android 项目在模拟器上崩溃?

android - 将 FragmentTransaction 与 DialogFragment 一起使用