我有一个附有 main.xml 的简单 Activity。main.xml 有一个自定义布局 (customLinearLayout) 和一个简单的 TextView。自定义布局也有自己的布局文件 (linearlayout.xml) 和一个简单的按钮。布局由类正确膨胀。
linearlayout.xml 中的 Button 将更改位于 main.xml 中的 textView 的文本,但我无法访问该 textView。我究竟做错了什么?我也不能膨胀 main.xml。
这是自定义线性布局:
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);
}
}
Activity 的 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>