java.lang.UnsupportedOperationException:不支持addView(View)

时间:2016-03-10 10:20:23

标签: android android-fragments gridview adapter

我创建了一个活动并添加了一个片段,对于那个片段我添加了带有图像的gridview,当点击图像片段时应该打开但是我的片段没有打开并且崩溃并显示上面的error.how要添加碎片到网格视图的项目

屏幕//此片段已添加到主要活动并具有带图像的网格视图

public class Screen extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    // TODO: Rename and change types and number of parameters
    public static Screen newInstance(String param1, String param2) {
        Screen fragment = new Screen();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public Screen() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.screen, container, false);
        int[] text = {R.string.temp, R.string.weight, R.string.len, R.string.time, R.string.area, R.string.vol, R.string.store, R.string.prsure, R.string.sound, R.string.ene, R.string.mag, R.string.img};
        int[] imgId = {R.drawable.temperature, R.drawable.food, R.drawable.resize, R.drawable.circular, R.drawable.pie, R.drawable.chemistry, R.drawable.database, R.drawable.blood, R.drawable.sound, R.drawable.energy, R.drawable.magnet, R.drawable.images};

        GridView grid = (GridView) view.findViewById(R.id.grid);
        Custom_Grid adapter = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            adapter = new Custom_Grid(getContext(), text, imgId);
        }

        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Fragment fragment;
                FragmentManager fm = getChildFragmentManager();
                switch (position) {
                    case 0:
                        fragment = new Temperature();
                        fm.beginTransaction().replace(R.id.grid,fragment).commit();
                        break;
                    case 1:
                        fragment = new Weight();
                        fm.beginTransaction().replace(R.id.grid,fragment).commit();
                        break;
                    case 2:
                        fragment = new Length();
                        fm.beginTransaction().replace(R.id.grid,fragment).commit();
                        break;
                    case 3:
                        fragment = new Time();
                        fm.beginTransaction().replace(R.id.grid,fragment).commit();
                        break;
                    case 4:
                        fragment = new Area();
                        fm.beginTransaction().replace(R.id.grid,fragment).commit();
                        break;
                    case 5:
                        fragment = new Volume();
                        fm.beginTransaction().replace(R.id.grid,fragment).commit();
                        break;

                }
            }
        });
        return view;
    }


}

MainActivity:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

Fragment fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    Screen scr = new Screen();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.sun,scr);
    ft.commit();

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

logcat的

java.lang.UnsupportedOperationException:AdapterView不支持addView(View) 03-10 05:58:23.188 24381-24381 / com.example.cherrypandu.uc E / AndroidRuntime:在android.widget.AdapterView.addView(AdapterView.java:469) 03-10 05:58:23.188 24381-24381 / com.example.cherrypandu.uc E / AndroidRuntime:at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)

    public class Custom_Grid extends BaseAdapter
{
    private Context mContext;
    private final int[] text;
    private final int[] Imageid;

    public Custom_Grid(Context c, int[] text, int[] Imageid) {
        mContext = c;
        this.Imageid = Imageid;
        this.text=text;
    }

    @Override
    public int getCount() {
        return text.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
            textView.setText(text[position]);
            imageView.setImageResource(Imageid[position]);
        } else {
            grid = (View) convertView;
        }
        return grid;
    }

grid_single:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/grid_image"
        android:layout_marginTop="5dp"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="small text"
        android:layout_gravity="center"
        android:textSize="12sp"
        android:id="@+id/grid_text" />
</LinearLayout>

2 个答案:

答案 0 :(得分:0)

fragment = new Temperature();
fm.beginTransaction().replace(R.id.one,fragment).commit();
break;

这是找不到视图的地方。您应该提供添加片段的容器的ID,而不是 R.id.one

在您的示例中,我认为您应该用

替换它
fragment = new Temperature();
fm.beginTransaction().replace(R.id.CONTAINER_ID,fragment).commit();
break;

EDI ***:其中CONTAINER_ID正是它听起来的样子,即片段的容器。只需在xml中声明它的id。

还要注意这一部分:

Custom_Grid adapter = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        adapter = new Custom_Grid(getContext(), text, imgId);
    }

    grid.setAdapter(adapter);

如果您的构建版本不符合此术语,则最终可能会出现 NullPointerException

答案 1 :(得分:0)

在xml布局中将FrameLayout定义为片段的容器并为其设置id。 然后在你的交换机开发中使用这个id,如下所示:

 case 0:
                    fragment = new Temperature();
                    fm.beginTransaction().replace(R.id.framelayoutId,fragment).commit();
                    break;