findViewById的问题

u012914916 2016-01-26 12:04:09
请问,这个,直接用findViewById正常显示列表,用p1.findViewById就不显示了,都不是null值,为什么呢??哪位大兄弟给我说一说啊,谢谢。
res/layout/里有p1.xml。

public class MainActivity extends ActionBarActivity {
private View mPopMenuView;
private PopupWindow mPopWindow;

private LinearLayout p1;
private LinearLayout p2;
private LinearLayout p3;
private ListView p1List; //屏1的列表

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(R.layout.p1);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true); //显示导航的返回按钮

//屏1的列表
try {
p1 = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.p1, null);
if(p1 == null){
Log.e("自定义错误","p1为null");
}else{
Log.e("自定义错误","p1不为null");
}
p1List = (ListView) p1.findViewById(R.id.p1_list);
if(p1List == null){
Log.e("自定义错误","p1List为null");
}else{
Log.e("自定义错误","p1List不为null");
}

BaseAdapter adapter = new BaseAdapter() {
Integer image[] = new Integer[]{R.drawable.dingding, R.drawable.dixi, R.drawable.lala, R.drawable.bo};
String username[] = new String[]{"张三", "李四", "王五", "赵六"};
String message[] = new String[]{"湖南 男 13", "北京 男 14", "广东 男 15", "厦门 男 16"};

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout p1ListLayout = null; //屏1列表项布局xml
if (convertView == null) {
p1ListLayout = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.p1_list, null);
} else {
p1ListLayout = (LinearLayout) convertView;
}

ImageView img = (ImageView) p1ListLayout.findViewById(R.id.header_img);
TextView text1 = (TextView) p1ListLayout.findViewById(R.id.username);
TextView text2 = (TextView) p1ListLayout.findViewById(R.id.message);
if(text1 == null){
Log.e("自定义错误","text2为null");
}else{
Log.e("自定义错误","text2不为null");
}

img.setImageResource(image[position]);
text1.setText(username[position]);
text2.setText(message[position]);

return p1ListLayout;
}

@Override
public int getCount() {
return username.length;
}

@Override
public String getItem(int position) {
return username[position];
}

@Override
public long getItemId(int position) {
return position;
}
};
p1List.setAdapter(adapter);
}catch (Exception e){
Log.e("p1List",Log.getStackTraceString(e));
}
}
...全文
184 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
林深 2016-01-26
  • 打赏
  • 举报
回复
p1 = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.p1, null); 这步操作是新建了一个由R.layout.p1这个layout表现的view,注意是新建,并不是使用当前activity所在的contentview,,所以嘛,你从p1里面取到的p1List不是当前界面上的p1List。。。这完全是两个对象。。。
u012914916 2016-01-26
  • 打赏
  • 举报
回复
25行那里。 正常:p1List = (ListView) findViewById(R.id.p1_list); 不显示:p1 = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.p1, null); p1List = (ListView) p1.findViewById(R.id.p1_list);

80,359

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧