0

我试图个性化有关布局更改的 Android 教程(http://developer.android.com/training/animation/layout.html),但在代码中有这段代码

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        // Navigate "up" the demo structure to the launchpad activity.
        // See http://developer.android.com/design/patterns/navigation.html
        // for more.
        NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
        return true;

    case R.id.action_add_item:
        // Hide the "empty" view since there is now at least one item in the
        // list.
        findViewById(android.R.id.empty).setVisibility(View.GONE);
        addItem();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

就我而言,菜单中没有按钮,但我会使用外部按钮。我试图使用这个按钮:

<Button
            android:id="@+id/buttonPost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="30dp"
            android:layout_toRightOf="@+id/editTextComment"
            android:text="Post"
            android:onClick="add" />

用方法

    public void add(View view) {
    findViewById(android.R.id.empty).setVisibility(View.GONE);
    addItem();

}

但是这个解决方案不起作用。有任何想法吗?

4

2 回答 2

2

onOptionsItemSelectedmenu用于与. 一起使用的选项onCreateOptionsMenu(Menu menu)。如果您onClick希望它适用于Buttons和switch.Button id

public void add(View v) {

   switch (v.getId()) {
   case R.id.buttonPost:
        findViewById(android.R.id.empty).setVisibility(View.GONE);
        addItem();
        break;
    case R.id.another_button_id:
        // do something else
        break;
    }

}
于 2013-06-28T15:14:41.357 回答
0

OnClickListener而是在您的按钮上放置一个:

findViewById(R.id.buttonPost).setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // do something here
    }
});
于 2013-06-28T15:33:11.670 回答