在要引用的布局内没有控件要求相应事件,在目标布局的 xml
文件中添加:
AخA<include layout="@layout/layoutname" />
否则
新建 JAVA
类(创建自己的布局)
xpackage com.kl6g.uitest;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class TestLayout extends LinearLayout {
public TestLayout(final Context context, AttributeSet attrs) {
super(context, attrs);
// 其中infalte的第一个参数为要使用的布局文件
LayoutInflater.from(context).inflate(R.layout.test_layout, this);
Button btnsend = (Button) findViewById(R.id.btn_test_send);
btnsend.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
});
}
}
在目标布局的 XML
文件中添加(注意类名要写完整,包含包名)
xxxxxxxxxx
<com.kl6g.uitest.TestLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp" />
test_layout
内容
xxxxxxxxxx
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/button_send"
android:id="@+id/btn_test_send" />
</LinearLayout>