我在开发Android应用时遇到麻烦。我想重用本节许多其他活动。我找到了“布局充气”。而且我可以用它。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- Header Start -->
<RelativeLayout
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:padding="5dp"
android:background="#fff8f8ff">
<!-- Menu button -->
<Button
android:id="@+id/menuBtn"
android:layout_width="40dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:background="@drawable/menubtn"/>
<!-- Logo / Return to Main page -->
<Button
android:id="@+id/logoBtn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@drawable/ic_launcher"/>
<!-- Login Btn -->
<Button
android:id="@+id/loginBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/logoBtn"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#00FFFFFF"
android:text="Login"
android:textSize="20dp" />
</RelativeLayout>
<!-- End of Header -->
</RelativeLayout>
但是,现在!我有下一步的问题。如何设置和重用按钮监听器等活动。
// header button listener
Button menuBtn = (Button)findViewById(R.id.menuBtn);
Button logoBtn = (Button)findViewById(R.id.logoBtn);
Button loginBtn = (Button)findViewById(R.id.loginBtn);
menuBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Toast.makeText(getBaseContext(), "menu", Toast.LENGTH_SHORT).show();
}
});
logoBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Toast.makeText(getBaseContext(), "logo", Toast.LENGTH_SHORT).show();
}
});
loginBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Toast.makeText(getBaseContext(), "login", Toast.LENGTH_SHORT).show();
}
});
// End of header Button
我希望将该部分重用于其他活动。而我正试图导入系统,但我还没有。
很快,我想重用源代码(listener和xml)。我怎么能这样做?
答案 0 :(得分:1)
public class YourActivity extends Activity implements Button.OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menuBtn.setOnClickListener(this);
logoBtn.setOnClickListener(this);
loginBtn.setOnClickListener(this);
}
public void onClick(View v) {
if(menuBtn == v) {
showMyToast("menu");
}else if(logoBtn == v){
showMyToast("logo");
}else if(loginBtn == v){
showMyToast("login");
}
}
private void showMyToast(String str){
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}