0

我正在尝试检索一个视图,但它一直返回 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 = (view) .... 等处不断收到 NullPointerException。

4

2 回答 2

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 和任何其他控件。

于 2012-04-05T05:59:11.413 回答
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 的父布局。

于 2015-08-25T11:52:37.923 回答