问题
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 is what I have:
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container,false);
RelativeLayout rl1 = new RelativeLayout(view.getContext());
TextView tView1 = new TextView(view.getContext());
tView1.setText("test");
rl1.addView(tView1);
rl1.setId(1);
tView1.setId(2);
...
}
Then in the custom view I call the relative Layout and TextView by id. When I try to do anything, I get a NullPointer exception.
...
RelativeLayout rl1 = (RelativeLayout) findViewById(1);
TextView tView1 = (TextView) findViewById(2);
tView1.getText();
The code above shows trying to .getText()
on the TextView, but anything I do to the RelativeLayout also causes a NullPointer exception.
So basically, it looks like I'm not finding the RelativeLayout and TextViews correctly. FYI, I've already seen this similar question, but it didn't apply here, my constructors are already set up appropriately.
回答1:
You should be adding the Layout to the main View, however, you need to cast it first into a Layout:
YourLayout view = (YourLayout) inflater.inflate(R.layout.fragment1, container,false);
RelativeLayout rl1 = new RelativeLayout(view.getContext());
TextView tView1 = new TextView(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()
and onCreateView() has already been called:
RelativeLayout rl1 = (RelativeLayout) getView().findViewById(1);
TextView tView1 = (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.
回答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
来源:https://stackoverflow.com/questions/14913973/nullpointerexception-when-accessing-relativelayout-from-a-custom-view