我正在尝试检索一个视图,但它一直返回null,我该如何找到它?
public class TripDailyItinerary extends Activity {
ViewGroup layout;
View v;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.html_content);
TextView content = (TextView) findViewById(R.id.htmlContent);
layout = (ViewGroup) findViewById(R.layout.trip_content);
v = (View) layout.findViewById(R.id.bg); //where the error is
JSONObject reservation;
int resNumber = ((MyApp) this.getApplication()).getResNum();
String dailyitinerary = "";
try {
reservation = ((MyApp) this.getApplication()).getJSON().getJSONObject("response").getJSONArray("reservations").getJSONObject(resNumber);
dailyitinerary = reservation.getString("dailyitinerary");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
content.setText(Html.fromHtml(dailyitinerary));
}
}
我在v =(查看)等等时继续得到NullPointerException。
答案 0 :(得分:0)
layout = (ViewGroup) findViewById(R.layout.trip_content);
v = (View) layout.findViewById(R.id.bg); //where the error is
用下面的
替换上面两行LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view view = inflater.inflate(R.layout.R.layout.trip_content,null);
TextView name = (TextView) view.findViewById(R.id.bg);
TextView可以用你的控件替换ImageView和任何其他。
答案 1 :(得分:0)
使用此:
ViewGroup parent = (ViewGroup)findViewById(R.id.trip_layout);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.trip_content,parent);
如果要添加TextView
TextView content = (TextView)myView.findViewById(R.id.htmlContent);
因为null
发出警告..
R.id.trip_layout
是XML Layout的父布局。