将类转换为接口

发布于 2024-11-04 09:15:22 字数 7876 浏览 0 评论 0原文

请帮助我了解如何将我的类转换为界面,以便其他类可以使用主菜单。或者让我知道是否有简单的方法可以在主类中调用相同的菜单,除了扩展 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);
    }
}

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

现在我能够收到登录错误,它们是 在此处输入图像描述

please help me about that how i can convert my class into interface so other classes can use main menu . or let me know if there is easy way to call the same menu in the main class except extends bcz there are classes which already are extending other classes. here is the sample code

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;
    }
}

i want to call these menus into other classes (one of them are listed below) so that option menu is available on every activity without using extends.

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(); 

            }
        });
    }
}

now i am following this way

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;
}

}
and Test class is

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);
    }
}

menu are perfectly appearing on the screen but when i am clicking on any menu it "Force to stop" pops up

Now i am able to get logat errors Here they are
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

灯角 2024-11-11 09:15:22

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

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);
    }
}

What I would do is create a special class to handle menu creation and events and delegate everythng to it. The code will look like this:

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
    }
}

Then when you need to have a menu in your Activity, you create MenuHandler and delegate method calls to it:

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);
    }
}
花开浅夏 2024-11-11 09:15:22

接口没有实现,所以我认为这不会达到您想要的效果。

您可以做的是创建一个扩展 ControlMenu 的活动。它将是一个活动(因为 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() {}       

}

An interface does not have an implementation, so I don't think that will do what you want.

What you can do is make an activity that extends your ControlMenu. It will be an Activity (because controlmenu itself extends activity), and it will be able to use the code you have provided here. It will look something like

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)); 
    }
}

and you'll have an adapter that goes like (quick mock-up)

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() {}       

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文