动态添加自定义大小的片段

时间:2016-01-21 17:51:00

标签: java android

我在主活动中添加了一个片段,但我希望该片段仅占用活动屏幕的上半部分。我怎么做? 主要活动:

    public class MainActivity extends Activity {

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

    FragmentManager fm = getFragmentManager();

    if (fm.findFragmentById(android.R.id.content) == null) {
        SimpleListFragment list = new SimpleListFragment();
        fm.beginTransaction().add(android.R.id.content, list).commit();
    }
}
}

SimpleListFragment.java:

    public class SimpleListFragment extends ListFragmen{

String[] numbers_text = new String[] { "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine", "ten", "eleven",
        "twelve", "thirteen", "fourteen", "fifteen" };
String[] numbers_digits = new String[] { "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "10", "11", "12", "13", "14", "15" };

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    //new CustomToast(getActivity(), numbers_digits[(int) id]);
    //ListViewItem item = mItems.get(position);

    // do something
    Toast.makeText(getActivity(), numbers_digits[(int) id], Toast.LENGTH_SHORT).show();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            inflater.getContext(), android.R.layout.simple_list_item_1,
            numbers_text);
    setListAdapter(adapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}
}

我修改了content_main.xml:

    <Relative Layout>

       ...

    <FrameLayout>
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="vertical">
    </FrameLayout>
    </Relativelayout>

并将代码更改为fm.beginTransaction()。add(R.id.frameLayout,list).commit();

然而它给了我一个错误:

java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.nazar.listfragment / com.example.nazar.listfragment.MainActivity}:java.lang.IllegalArgumentException:找不到id 0x7f0c006b的视图(com.example .nazar.listfragment:id / frameLayout)用于片段SimpleListFragment {554506b#0 id = 0x7f0c006b

1 个答案:

答案 0 :(得分:0)

你的片段是一个列表,为什么不只是使用ListView呢?

无论如何,要使片段只有屏幕大小的一半,您应该添加一个FrameLayout,其大小与您希望的Activity布局相同,然后在该布局上插入片段。

 fm.beginTransaction().add(R.id.frameLayout, list).commit();