【问题标题】:Can't start activity from class无法从课堂开始活动
【发布时间】:2011-09-27 12:29:40
【问题描述】:

我正在尝试从普通班级开始一项活动,但我无法弄清楚它是如何完成的,如果可以完成的话。在 itemClick 上,我想启动一个扩展 ListView 类以显示选项列表的活动。

接收 onItemClick 的类也不是一个活动。我将发布代码以尝试可视化我的意思。

这是我想要启动活动的类中的 onClick 方法。

public void onClick(View v) {
        if (v.equals(this)) {
            notifyObservers(this.getId());
        } else if(v.equals(editButton) || v.equals(deleteButton)) {
            This is where I want to start the activity to show my ListView...
        }

}

这是我的扩展 ListView 类的类。

public class ProfileSettings extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] mainSettings = getResources().getStringArray(R.array.mainSettings);

        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mainSettings));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Do something
            }
        });
    }
}

提前致谢!

【问题讨论】:

标签: android class android-activity onitemclick


【解决方案1】:

我认为这可能会对您有所帮助:

“通过构造函数将活动的上下文传递给您的类或在您的活动中创建静态上下文。 使用上下文,您可以像在 Activity 类中启动它们一样启动 Activity。"

    class First extends Activity {
    ...
    Second test = new Second(this);
    test.start();
    ...
}

class Second {
    private Context mContext;
    ...
    public Second(Context c) { this.mContext = c; }
    ...
    public start() { mContext.startActivity(...); }
}

更多细节检查

http://www.anddev.org/view-layout-resource-problems-f27/starting-an-activity-from-a-non-activity-class-t14483.html

【讨论】:

    【解决方案2】:

    在你的 onClick 中试试这个

    Intent i = new Intent(this, ProfileSettings.class);
    startActivity(i);
    

    编辑:

    也不要忘记将活动添加到您的清单中。

    【讨论】:

    • 别忘了将新活动添加到 android 清单中
    • 我不认为你可以从非活动类调用 startActivity。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多