我有一个简单的Activity,它附带了main.xml。main.xml具有自定义布局(customLinearLayout)和一个简单的TextView。自定义布局也有它自己的布局文件(linearlayout.xml),其中包含一个简单的Button。该布局被类正确地膨胀。
linearlayout.xml中的Button应更改位于main.xml中的textView的文本,但我无法访问该textView。我做错了什么?我也无法膨胀main.xml。
这是customLinearLayout:
活动的 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>