我有一个简单的活动及其附带的main.xml。 main.xml有一个自定义布局(customLinearLayout)和一个简单的TextView。自定义布局也有其自己的布局文件(linearlayout.xml)和一个简单的Button。这个布局是正确的膨胀。如何从膨胀布局访问视图?
linearlayout.xml中的按钮应更改位于main.xml中的textView的文本,但我无法访问该textView。我究竟做错了什么?我也无法膨胀main.xml。
这里的customLinearLayout:
public class CustomLinearLayout extends LinearLayout {
LayoutInflater mInflater;
View ContainerView;
Button button1;
TextView tv;
public CustomLinearLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
init();
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
private void init() {
mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ContainerView = mInflater.inflate(R.layout.linearlayout, this, true);
button1 = (Button) ContainerView.findViewById(R.id.button1);
// trying to get the TextView from main.xml
tv = (TextView) ContainerView.findViewById(R.id.textview1); // doesn't work
// these tries doesn't work either
//tv = (TextView) ContainerView.getRootView().findViewById(R.id.textview);
//tv = (TextView) this.getRootView().findViewById(R.id.textview);
//tv = (TextView) this.findViewById(R.id.textview);
button1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(tv != null)
tv.setText("works");
else
Log.d("CustomLinearLayout", "TextView not found");
}
});
}
}
布局文件(linearlayout.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="press" />
</LinearLayout>
的活动:
public class TestLayoutViewsv2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
该活动的main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<test.layoutviewsv2.CustomLinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
谢谢你的回答!我想我的想法是错误的。我认为这些视图会在膨胀后加入main.xml,以便我可以回到层次结构。我想我必须阅读使用回调然后。是否有任何其他方式让视图知道另一个视图已经改变? (例如,告诉按钮切换回初始状态,当另一个视图或课程完成他的工作) – user1349812 2012-04-22 22:23:22
@ user1349812 nope,这几乎是唯一的方法 - >您的活动管理其所有视图的状态。就像我说的那样,这个观点存在于它自己的小世界中 - 它可以告诉母亲发生了什么事情,母亲的工作是根据所收到的信息确保所有相关的其他观点发生变化 – JRaymond 2012-04-23 00:36:02
但是不会意思是说,只有一个控制所有UI的层次结构层?为了避免重载的Activity,将UI分解成一些ViewGroups的想法如何?这是如何处理的? - 最后一个问题我保证:) – user1349812 2012-04-23 08:42:41