Skip to content Skip to sidebar Skip to footer

Nullpointerexception When Accessing Relativelayout From A Custom View

I am relatively new to Android and am completely stuck on how to access my programmatically-defined Relative Layout (defined in a fragment) in my custom View. In the fragment, this

Solution 1:

You should be adding the Layout to the main View, however, you need to cast it first into a Layout:

YourLayoutview= (YourLayout) inflater.inflate(R.layout.fragment1, container,false);
RelativeLayoutrl1=newRelativeLayout(view.getContext());
TextViewtView1=newTextView(view.getContext()); 
tView1.setText("test");
rl1.addView(tView1); 
rl1.setId(1);
tView1.setId(2);
view.addView (rl1);//add rl1 to the main View

Then to access, if you're working outside onCreateView()andonCreateView() has already been called:

RelativeLayoutrl1= (RelativeLayout) getView().findViewById(1);
TextViewtView1= (TextView) rl1.findViewById(2);
tView1.getText();

If you're still trying to access the views in onCreateView(), findViewById() doesn't matter - you already have the references of your Views so use those.

It's also worth noting that adding listeners and such in onCreateView() to update the UI can be done, so you may be able to simply things a bit.

Solution 2:

You have to add your Relative layout to your layout group... And from the parent view of your layout you can access your relative layout and its childs

Post a Comment for "Nullpointerexception When Accessing Relativelayout From A Custom View"