how do I findviewbyid of a view inside a tabhost from an activity thats inside the tabhost?

感情迁移 提交于 2019-12-11 16:27:08

问题


I'm trying to retrieve a view but it keeps returning null, how do I find it?

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));
}

}

I keep getting a NullPointerException at v = (view) .... etc.


回答1:


layout = (ViewGroup) findViewById(R.layout.trip_content);
v = (View) layout.findViewById(R.id.bg); //where the error is

replace the above two lines with below

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);

also TextView can be replaced with your control either ImageView and any other.




回答2:


Use this :

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);

If you want to add TextView

TextView content = (TextView)myView.findViewById(R.id.htmlContent);

Because the null makes warning ..

R.id.trip_layout is the parent layout of your XML Layout .



来源:https://stackoverflow.com/questions/10023058/how-do-i-findviewbyid-of-a-view-inside-a-tabhost-from-an-activity-thats-inside-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!