将类转换为接口

时间:2011-04-30 10:53:51

标签: java android

请帮我解释一下如何将我的类转换为界面,以便其他类可以使用主菜单。或者让我知道是否有简单的方法来调用主类中的相同菜单,除了扩展bcz之外,还有已经扩展其他类的类。这是示例代码

package com.droidnova.android.howto.optionmenu;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class ControlMenu extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings:     
                Intent intent = new Intent(this, ShowSettings.class);
                  startActivity(intent);
            break;
            case R.id.services:     
                Intent intent2 = new Intent(this, Test.class);
                startActivity(intent2);
              break;
            case R.id.Quit: 

                finish();



                break;
            default:    
            break;
        }
        return true;
    }
}

我想将这些菜单调用到其他类中(其中一个列在下面),以便每个活动都可以使用选项菜单而不使用扩展名。

public class Test extends ListActivity  {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");

        try{

            JSONArray  earthquakes = json.getJSONArray("earthquakes");

            for(int i=0;i<earthquakes.length();i++){                        
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = earthquakes.getJSONObject(i);

                map.put("id",  String.valueOf(i));
                map.put("name", "Earthquake name:" + e.getString("name"));
                map.put("password", "Magnitude: " +  e.getString("password"));
                mylist.add(map);            
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test, 
                        new String[] { "name", "magnitude" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });
    }
}

现在我按照这种方式

package com.droidnova.android.howto.optionmenu;

import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;

public class MenuHandler extends Activity{
    private Activity activity;

    public MenuHandler(Activity activity) {
        this.activity = activity;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = activity.getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

     public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.settings:     
            Intent intent = new Intent(this, ShowSettings.class);
              startActivity(intent);
        break;
        case R.id.services:     
            Intent intent2 = new Intent(this, Test.class);
            startActivity(intent2);
          break;
        case R.id.Quit: 

            finish();



            break;
        default:    
        break;
    }
    return true;
}

} 和测试类是

package com.droidnova.android.howto.optionmenu;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Test extends ListActivity  {
    private MenuHandler menuHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
        menuHandler = new MenuHandler(this);
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");

        try{

            JSONArray  earthquakes = json.getJSONArray("earthquakes");

            for(int i=0;i<earthquakes.length();i++){                        
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = earthquakes.getJSONObject(i);

                map.put("id",  String.valueOf(i));
                map.put("name", "Earthquake name:" + e.getString("name"));
                map.put("password", "Magnitude: " +  e.getString("password"));
                mylist.add(map);            
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test, 
                        new String[] { "name", "magnitude" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return menuHandler.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return menuHandler.onOptionsItemSelected(item);
    }
}

菜单完美地出现在屏幕上,但当我点击任何菜单时,会弹出“强制停止”

现在我能够获得logat错误 enter image description here

2 个答案:

答案 0 :(得分:2)

我要做的是创建一个特殊的类来处理菜单创建和事件,并将everythng委托给它。代码如下所示:

public class MenuHandler {
    private Activity activity;

    public MenuHandler(Activity activity) {
        this.activity = activity;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = activity.getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        //Handle events here
    }
}

然后,当您需要在Activity中添加菜单时,您需要创建MenuHandler并委托方法调用:

public MyActivity extends Activity {
    private MenuHandler menuHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        menuHandler = new MenuHandler(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return menuHandler.onCreateOprionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return menuHandler.onOptionsItemSelected(item);
    }
}

答案 1 :(得分:1)

接口没有实现,所以我认为这不会做你想要的。

您可以做的是进行扩展ControlMenu的活动。它将是一个Activity(因为controlmenu本身扩展了活动),它将能够使用您在此处提供的代码。它看起来像

public class yourActivity extends ControlMenu{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); //oncreate of controlmenu
        LayoutInflater inflater = getLayoutInflater();
        RelativeLayout ll = (RelativeLayout) findViewById(R.id.main);
        ListView lv = (ListView) inflater.inflate(R.layout.yourlistview, ll, false);
        ll.addView(lv);
        lv.setAdapter(new YourAdapter(this)); 
    }
}

你将拥有一个类似于(快速模型)的适配器

public abstract class YourAdapter extends BaseAdapter {

   final public int getCount() {}
   final public Object getItem(int position) {}
   final public long getItemId(int position) {}
   final public void onItemClick() {}       

}