从片段类访问UI元素

时间:2014-03-10 03:23:48

标签: android android-fragments

我有一个扩展片段类的类,如下所示:

public class FragmentCreateGroup extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        ImageView group=(ImageView)findViewById(R.id.group_image);//shows error here

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_creategroup, container,false);
    }

}

与以下xml文件

相关联
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/cr_group_grpname_desc"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/group_image"
        android:layout_width="139dp"
        android:layout_height="144dp"
        android:src="@drawable/background" />

    <EditText
        android:id="@+id/cr_group_grpname_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="37dp"
        android:contentDescription="@string/cr_group_grpname_desc"
        android:ems="10"
        android:hint="@string/cr_group_grpname_hint"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/cr_group_creategrp_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="42dp"
        android:background="@drawable/greenbutton"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="@string/cr_group_creategrp_btn_label" />

</LinearLayout>

我尝试使用findViewById()访问片段布局中的ImageView。由于我没有扩展Activity类,因此我无法执行此操作。有没有办法从非活动类访问UI元素?如果有什么表现?

1 个答案:

答案 0 :(得分:2)

您需要在onCreateView

中充气后获取视图
public class FragmentCreateGroup extends Fragment {

private ImageView group;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_creategroup, container, false);
    group = (ImageView) v.findViewById(R.id.group_image);
    group.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            group.setImageDrawable(); // set image here
        }
    });
    return v;
}

}