我正在学习如何使用片段制作标签的教程。 每个标签在java文件中都有这个:
公共类rdfri扩展Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment's containing frame doesn't exist. The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won't be displayed. Note this is not needed -- we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}
return (LinearLayout)inflater.inflate(R.layout.rdfri, container, false);
}
}
我想尝试在片段中获取一个imageButton。我认为图像处理器使用此代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rdmon);
ImageButton rainbowbook =(ImageButton)findViewById(R.id.imageButton1);
rainbowbook.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = Intent(rdmon.this, RainbowBookActivity.class);
rdmon.this.startActivity(myIntent);
}
});
}
那么如何获取片段代码中的按钮代码呢?
感谢。
答案 0 :(得分:0)
将按钮代码放在片段类中重写的onActivityCreated
方法中。
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ImageButton rainbowbook = (ImageButton) findViewById(R.id.imageButton1);
rainbowbook.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = Intent(rdmon.this, RainbowBookActivity.class);
rdmon.this.startActivity(myIntent);
}
});
}
这当然假定您的图像按钮包含在片段布局中。