0

I have a problem when creating dynamically an imageview from a fragment. Here is the code:

public class Fragment_Categorize extends Fragment implements View.OnDragListener, View.OnLongClickListener {
Context context;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment__categorize, container, false);

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    context = getActivity().getApplicationContext();

    ImageView imm = new ImageView(context);
    imm.setBackgroundResource(R.drawable.apple);

    ImageView black = (ImageView) getActivity().findViewById(R.id.black);
    black.setOnLongClickListener(this);

The imageview that is created dynamically returns -1 on a getId() where the static one works fine. Any reason why?

enter image description here

narb
  • 958
  • 1
  • 13
  • 39

1 Answers1

1

Because you did not set an id for the dinamical one, you've just set a background.

Check this answer for setting the id dynamically: link

Community
  • 1
  • 1
abbath
  • 2,444
  • 4
  • 28
  • 40
  • Thanks. I thought you did'nt need an entry in the layout file? – narb Dec 11 '15 at 10:19
  • I think you can set a custom integer id as well, but that can cause troubles if there's an other view with a same generated id. So the safe way would be the one suggested under the other post, with creating the ids.xml. Although you can check in your R.java for which id-s are already used, and add such ones dynamically that can't overlap the generated ones. But if I remember well, R.java is regenereated a lot of times, so that can cause problems. – abbath Dec 11 '15 at 15:09