0

我感到困惑的包括佈局:公共代碼包括佈局 - (例動作條)

  1. 比方說,我做了一個名爲actionbar.xml
  2. 一個操作欄的佈局我包括這一切我其他佈局

現在我該如何以及在哪裏編寫用於操作欄的Java代碼?如果我寫onclick-功能說main.java

我怎樣才能使用相同的說,第二個活動存儲在second.java?有沒有其他的方法,而不是做一個類的對象,其中定義了操作欄的onclick

+0

請清楚您的問題 – Goofy 2012-03-30 07:03:28

+1

爲您的操作欄發佈XML代碼,我們可以解釋 – Blundell 2012-03-30 07:11:53

回答

0

有辦法實現這一點。你應該爲你的操作欄實現一個相間回調函數。

2

如果你有一個action_bar.xml佈局是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<com.your.package.ui.widget.ActionBar xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/actionBar" 
    android:layout_width="fill_parent" 
    android:layout_height="58dip" 
    android:background="@drawable/action_bar_background" > 

<ImageButton 
     android:id="@+id/actionBarOpenButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@color/transparent" 
     android:contentDescription="open button" 
     android:src="@drawable/action_bar_open_button" /> 

</com.your.package.ui.widget.ActionBar> 

你將不得不在包裝com.your.package.ui.widget

調用ActionBar.java,看上去像這樣一類:

package com.your.package.ui.widget; 

public class ActionBar extends LinearLayout implements OnClickListener { 

    public ActionBar(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public ActionBar(Context context) { 
     super(context); 
    } 

     @Override 
     protected void onFinishInflate() { 
      super.onFinishInflate(); 

      findViewById(R.id.actionBarOpenButton).setOnClickListener(this); 
     } 

    @Override 
     public void onClick(View v) {     
      switch (v.getId()) { 
      case R.id.actionBarOpenButton: 
        // Do something 
        break; 
       default: 
       break; 
      } 
     } 
} 

你會然後將其包含在另一個佈局中,如下所示:`activity_main.xml':

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <include layout="@layout/action_bar" /> 

    <!-- Rest of your layout --> 

</LinearLayout> 

然後,您可以將它包含在您想要的任何Actvitity中,並且您的自定義小部件將在各處執行相同的onClick事件。